[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> 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; 
    }
}