zoukankan      html  css  js  c++  java
  • [LC] 743. Network Delay Time

    There are N network nodes, labelled 1 to N.

    Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.

    Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.

    class Solution {
        public int networkDelayTime(int[][] times, int N, int K) {
            Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
            for (int[] time: times) {
                if (!map.containsKey(time[0])) {
                    map.put(time[0], new HashMap<>());
                }
                map.get(time[0]).put(time[1], time[2]);
            }
            
            PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[0] - b[0]));
            boolean[] visited = new boolean[N + 1];
            int res = 0;
            
            pq.offer(new int[]{0, K});
            while (!pq.isEmpty()) {
                int[] curArr = pq.poll();
                int curNode = curArr[1];
                int curDist = curArr[0];
                if (visited[curNode]) {
                    continue;
                }
                N -= 1;
                res = curDist;
                visited[curNode] = true;
                // need to check unmapped node here
                if (map.containsKey(curNode)) {
                    for (int next: map.get(curNode).keySet()) {
                        pq.offer(new int[]{curDist + map.get(curNode).get(next), next});
                    }            
                }
            }
            return N == 0 ? res: -1; 
        }
    }
  • 相关阅读:
    课堂测试-单元测试(比较大小)
    第三周进度条
    软件工程个人作业02
    构建之法——阅读笔记02
    第二周学习进度条
    第一周学习进度条
    软件工程个人作业01
    构建之法阅读笔记01
    java课堂测试
    Java验证码程序
  • 原文地址:https://www.cnblogs.com/xuanlu/p/13063523.html
Copyright © 2011-2022 走看看