Back to DSA

Network Delay Time

medium
Acceptance: 50%
GraphsBFS

A directed weighted graph of n nodes has edges described as (source, destination, weight). A signal is broadcast from a given origin node. Determine the earliest time at which every node in the network has received the signal, or return -1 if some nodes are unreachable.

Examples

Example 1:
Input:times = [[1,2,3],[1,3,5],[2,3,1]], n = 3, k = 1
Output:4
Explanation: From node 1: reach node 2 in 3 and node 3 in min(5, 3+1) = 4. The latest arrival is 4.

Hints

00:00
import java.util.*;

class Solution {
    public int networkDelayTime(int[][] times, int n, int k) {
        Map<Integer, List<int[]>> graph = new HashMap<>();
        for (int[] t : times) graph.computeIfAbsent(t[0], x -> new ArrayList<>()).add(new int[]{t[1], t[2]});
        int[] dist = new int[n + 1];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[k] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
        pq.offer(new int[]{k, 0});
        while (!pq.isEmpty()) {
            int[] curr = pq.poll();
            int u = curr[0], d = curr[1];
            if (d > dist[u]) continue;
            if (graph.containsKey(u)) {
                for (int[] edge : graph.get(u)) {
                    int v = edge[0], w = edge[1];
                    if (dist[u] + w < dist[v]) {
                        dist[v] = dist[u] + w;
                        pq.offer(new int[]{v, dist[v]});
                    }
                }
            }
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) ans = Math.max(ans, dist[i]);
        return ans == Integer.MAX_VALUE ? -1 : ans;
    }
}
Time complexityO(E log V)
Space complexityO(V + E)