Practice LeetCode 743 · Network Delay Time · GFG · Dijkstra's Algorithm
GraphsGreedyWeightedMin-Heap

Dijkstra · Network Delay Time

Shortest paths from one source through non-negative weighted edges. Always expand the closest unsettled node, its distance is final, then relax its neighbors.

The greedy core

Keep a tentative distance for every node. Pull the smallest one from a min-heap, its distance can't improve anymore, so lock it in. Then try to shorten its neighbors' distances (relaxation).

Relaxation

  • Start: dist[src]=0, everything else ∞
  • Pop the min-distance node, settle it
  • For edge u→v: if dist[u]+w < dist[v], update
  • Push improved neighbors back into the heap

Settle nodes one by one

Unreached (∞) In heap (tentative) Settling Settled
Min-heap: empty
slowfast
Step 0
Settled
0
Settling
–
Heap size
0
Max dist
–

C++

int networkDelayTime(vector<vector<int>>& times, int n, int src) {
    vector<vector<pair<int,int>>> adj(n + 1);
    for (auto& t : times) adj[t[0]].push_back({t[1], t[2]});

    vector<int> dist(n + 1, INT_MAX);
    dist[src] = 0;
    priority_queue<pair<int,int>, vector<pair<int,int>>,
                   greater<>> pq;             // min-heap: {dist, node}
    pq.push({0, src});

    while (!pq.empty()) {
        auto [d, u] = pq.top(); pq.pop();
        if (d > dist[u]) continue;         // stale entry, skip
        for (auto& [v, w] : adj[u])
            if (dist[u] + w < dist[v]) {   // relax edge u→v
                dist[v] = dist[u] + w;
                pq.push({dist[v], v});
            }
    }

    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (dist[i] == INT_MAX) return -1;  // unreachable
        ans = max(ans, dist[i]);
    }
    return ans;                          // slowest arrival = network delay
}
Time
O(E log V)

Each edge triggers at most one heap push; heap ops are log V.

Space
O(V + E)

Adjacency list, distance array, and the priority queue.

Requires
w ≥ 0

Fails on negative edges. Use Bellman-Ford there.

  • Non-negative weights only. Dijkstra's greedy "settle the closest" logic breaks the moment a negative edge could retroactively shorten a settled node.
  • The if (d > dist[u]) continue guard is the lazy-deletion trick, cheaper than decrease-key on a binary heap.
  • Network Delay Time = the maximum shortest distance (last node to hear the signal). If any node is ∞, return -1.
  • For dense graphs an O(V²) array-scan Dijkstra can beat the heap version.
  • Add a parent array to reconstruct the actual shortest path, not just the distance.