相关信息:
LeetCode链接:
https://leetcode-cn.com/problems/second-minimum-time-to-reach-destination/
代码:
//作者:LeetCode-Solution
import java.util.*;
public class L2045 {
public static void main(String[] args) {
//Test
Solution2045 solution2045 = new Solution2045();
int n = 5;
int[][] edges = {{1, 2}, {1, 3}, {1, 4}, {3, 4}, {4, 5}};
int time = 3;
int change = 5;
int ans = solution2045.secondMinimum(n, edges, time, change);
System.out.println(ans);
}
}
class Solution2045 {
public int secondMinimum(int n, int[][] edges, int time, int change) {
List<Integer>[] graph = new List[n + 1];
for (int i = 0; i <= n; i++) {
graph[i] = new ArrayList<Integer>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
/*
* path[i][0] represents the shortest circuit length from 1 to i
* path[i][1] represents the strict secondary short circuit length from 1 to i
* */
int[][] path = new int[n + 1][2];
// Initialize path[i]
for (int i = 0; i <= n; i++) {
Arrays.fill(path[i], Integer.MAX_VALUE);
}
path[1][0] = 0;
//The elements stored in the queue are the destination and the distance to the destination [goal, distance]
Queue<int[]> queue = new ArrayDeque<>();
queue.offer(new int[]{1, 0});
/*Find the shortest number of times to reach the destination in the strict sense, and store it in path [n] [1]
* As long as path [n] [1] is not the default integer Max value,
* which indicates that the shortest number of times in the strict sense has been found
* */
while (path[n][1] == Integer.MAX_VALUE) {
int[] arr = queue.poll();
//cur is the current arrival point of the graph, and Len is the distance from the starting point to the next
int cur = arr[0], len = arr[1];
//graph[cur] is a list of elements directly connected to cur
for (int next : graph[cur]) {
if (len + 1 < path[next][0]) {
path[next][0] = len + 1;
queue.offer(new int[]{next, len + 1});
} else if (len + 1 > path[next][0] && len + 1 < path[next][1]) {
path[next][1] = len + 1;
queue.offer(new int[]{next, len + 1});
}
}
}
int ret = 0;
//On the basis of reaching the end point at least once. Count the waiting time
for (int i = 0; i < path[n][1]; i++) {
/*when you need to wait in the edges
* 2 * change is a cycle. The first change is the green light time and the second change is the red light time
* %2 * change is to eliminate the influence of RET in the previous cycle
* we need to determine is whether ret is currently in red light time,
* ret % (2 * change) < change it indicates that ret is in green time
* ret % (2 * change) < change it indicates that ret is in red time
* */
if (ret % (2 * change) >= change) {
/*Let ret become an integer multiple of the next minimum change greater than ret
* for example: ret = 6, change = 5
* The integer multiple of the minimum change greater than RET is 10
* */
ret = ret + (2 * change - ret % (2 * change));
}
ret = ret + time;
}
return ret;
}
}