题目20-python华为原题题库- 路口最短时间

华为 OD 机试:路口最短时间问题

题目描述

假定街道是棋盘型的,每格距离相等,车辆通过每格街道需要时间均为 timePerRoad
街道的街口(交叉点)有交通灯,灯的周期 T(=lights[row][col]) 各不相同;
车辆可直行、左转和右转,其中直行和左转需要等相应 T 时间的交通灯才可通行,右转无需等待。

现给出 n*m 个街口的交通灯周期,以及起止街口的坐标,计算车辆经过两个街口的最短时间。

其中:
1)起点和终点的交通灯不计入时间,且可以任意方向经过街口
2)不可超出 n*m 个街口,不可跳跃,但边线也是道路(即 lights[0][0] -> lights[0][1] 是有效路径)

入口函数定义:

/**
* lights : n*m 个街口每个交通灯的周期,值范围[0,120],n 和 m 的范围为[1,9]
* timePerRoad : 相邻两个街口之间街道的通过时间,范围为[0,600]
* rowStart : 起点的行号
* colStart : 起点的列号
* rowEnd : 终点的行号
* colEnd : 终点的列号
* return : lights[rowStart][colStart] 与 lights[rowEnd][colEnd] 两个街口之间的最短通行时间
*/
int calcTime(int[][] lights,int timePerRoad,int rowStart,int colStart,int rowEnd,int colEnd)

示例一

输入
[[1,2,3],[4,5,6],[7,8,9]],60,0,0,2,2
输出
245
说明

行走路线为 (0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2) 走了 4 格路,2 个右转,1 个左转,共耗时 60+0+60+5+60+0+60=245。

Code

from collections import namedtuple

MAX_INT = float('inf')
DIRECTIONS = [(0, -1), (1, 0), (0, 1), (-1, 0)]

Point = namedtuple('Point', ['x', 'y', 'direction', 'min_distance'])


def calcTime(lights, timePerRoad, rowStart, colStart, rowEnd, colEnd):
    max_row = len(lights)
    max_col = len(lights[0])
    result = [[[MAX_INT] * 4 for _ in range(max_row)] for _ in range(max_col)]
    print(result)
    pq = []
    for i in range(4):
        pq.append(Point(rowStart, colStart, i, 0))

    while pq:
        p = pq.pop(0)

        if p.min_distance > result[p.x][p.y][p.direction]:
            continue

        for i in range(4):
            newDir = (p.direction + i) % 4
            newX = p.x + DIRECTIONS[newDir][0]
            newY = p.y + DIRECTIONS[newDir][1]

            if 0 <= newX < max_row and 0 <= newY < max_col:
                newSpeed = p.min_distance + timePerRoad + (lights[p.x][p.y] if i != 1 else 0)
                if newSpeed < result[newX][newY][newDir]:
                    result[newX][newY][newDir] = newSpeed
                    pq.append(Point(newX, newY, newDir, newSpeed))

    return min(result[rowEnd][colEnd])


lights = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
timePerRoad = 60
rowStart, colStart = 0, 0
rowEnd, colEnd = 2, 2

print(calcTime(lights, timePerRoad, rowStart, colStart, rowEnd, colEnd))

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值