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;
    }
}
posted @ 2022-01-26 22:06  Frontierone  阅读(38)  评论(0编辑  收藏  举报