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; 
        }
    }
  • 相关阅读:
    Zookeeper 系列(一)基本概念
    深入浅出 JMS(三)
    深入浅出 JMS(四)
    深入浅出 JMS(三)
    深入浅出 JMS(二)
    深入浅出 JMS(一)
    git 记住用户名和密码
    13 Maven 编写插件
    12 Maven 生成项目站点
    11 Maven 灵活的构建
  • 原文地址:https://www.cnblogs.com/xuanlu/p/13063523.html
Copyright © 2011-2022 走看看