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; 
        }
    }
  • 相关阅读:
    强制类型转换
    《thinking in java》 接口与内部类
    JAVA强制类型转换(转载+自己的感想)
    Java 面试题问与答:编译时与运行时
    Java注解处理器
    Java反射详解
    BZOJ5072:[Lydsy1710月赛]小A的树(树形DP)
    BZOJ4987:Tree(树形DP)
    BZOJ3791:作业(DP)
    BZOJ1972:[SDOI2010]猪国杀(模拟)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/13063523.html
Copyright © 2011-2022 走看看