LeetCode 2045. 到达目的地的第二短时间
2045. 到达目的地的第二短时间
Solution
思路:求路径 然后再根据路径的长度算时间。这里使用BFS
来维护最短路和次短路,然后根据次短路的长度来计算总时间。
class Solution {
public int secondMinimum(int n, int[][] edges, int time, int change) {
List<Integer>[] graph = new List[n + 1];
for (int i = 1; i <= n; i++) {
graph[i] = new ArrayList<>();
}
for (int [] e: edges) {
graph[e[0]].add(e[1]);
graph[e[1]].add(e[0]);
}
int [][] path = new int[n + 1][2];
for (int i = 1; i <= n; i++) {
Arrays.fill(path[i], Integer.MAX_VALUE);
}
path[1][0] = 0;
Queue<int[]> queue = new ArrayDeque<>();
queue.offer(new int[]{1, 0});
while (path[n][1] == Integer.MAX_VALUE) {
int [] f = queue.poll();
int u = f[0], dist = f[1];
for (int v: graph[u]) {
if (dist + 1 < path[v][0]) {
path[v][0] = dist + 1;
queue.offer(new int[]{v, dist + 1});
} else if (dist + 1 > path[v][0] && dist + 1 < path[v][1]) {
path[v][1] = dist + 1;
queue.offer(new int[]{v, dist + 1});
}
}
}
int ans = 0;
for (int i = 1; i <= path[n][1]; i++) {
if (ans % (2 * change) >= change) {
ans += 2 * change - (ans % (2 * change));
}
ans += time;
}
return ans;
}
}
埋骨何须桑梓地,人生无处不青山