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; 
        }
    }
  • 相关阅读:
    安卓笔记20170117
    android笔记20170116
    meta 标签的作用
    SASS 初学者入门
    JQuery selector
    浅谈js回调函数
    自己写的jquery 弹框插件
    魔兽种子
    html页面的CSS、DIV命名规则
    各种弹框素材的链接
  • 原文地址:https://www.cnblogs.com/xuanlu/p/13063523.html
Copyright © 2011-2022 走看看