题目描述
假定街道是棋盘型的,每格距离相等,车辆通过每格街道需要时间均为 timePerRoad;
街道的街口(交叉点)有交通灯,灯的周期 T(=lights[row][col]) 各不相同;
车辆可直行、左转和右转,其中直行和左转需要等相应 T 时间的交通灯才可通行,右转无需等待。
现给出 n*m 个街口的交通灯周期,以及起止街口的坐标,计算车辆经过两个街口的最短时间。
其中:
1)起点和终点的交通灯不计入时间,且可以任意方向经过街口 不可超出 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。
import java.util.*;
public class Main {
static final int MAX_SPEED = Integer.MAX_VALUE;
enum Direction { UP, RIGHT, DOWN, LEFT };
static class Point {
int x, y, direction, speed;
public Point(int x, int y, int direction, int speed) {
this.x = x;
this.y = y;
this.direction = direction;
this.speed = speed;
}
}
static class Compare implements Comparator<Point> {
public int compare(Point a, Point b) {
return Integer.compare(a.speed, b.speed);
}
}
static int calcTime(int[][] lights, int timePerRoad, int rowStart,
int colStart, int rowEnd, int colEnd) {
int[][][] result = new int[rowEnd + 1][colEnd + 1][4];
for (int[][] row : result) {
for (int[] col : row) {
Arrays.fill(col, MAX_SPEED);
}
}
PriorityQueue<Point> pq = new PriorityQueue<>(new Compare());
for (int i = 0; i < 4; i++) {
pq.add(new Point(rowStart, colStart, i, 0));
}
int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
while (!pq.isEmpty()) {
Point p = pq.poll();
if (p.speed > result[p.x][p.y][p.direction]) {
continue;
}
for (int i = 0; i < 4; ++i) {
int newDir = (p.direction + i) % 4;
int newX = p.x + directions[newDir][0];
int newY = p.y + directions[newDir][1];
if (newX >= 0 && newX <= rowEnd && newY >= 0 && newY <= colEnd) {
int newSpeed = p.speed + timePerRoad + (i != 1 ? lights[p.x][p.y] : 0);
if (newSpeed < result[newX][newY][newDir]) {
result[newX][newY][newDir] = newSpeed;
pq.add(new Point(newX, newY, newDir, newSpeed));
}
}
}
}
return Math.min(Math.min(result[rowEnd][colEnd][0], result[rowEnd][colEnd][1]),
result[rowEnd][colEnd][2]);
}
public static void main(String[] args) {
int[][] lights = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int timePerRoad = 60;
int rowStart = 0;
int colStart = 0;
int rowEnd = 2;
int colEnd = 2;
System.out.println(calcTime(lights, timePerRoad, rowStart, colStart, rowEnd, colEnd));
}
}
246

被折叠的 条评论
为什么被折叠?



