Dijkstra's algorithm
Pattern: Shortest paths
With non-negative weights, repeatedly settle the unsettled vertex with the smallest known distance (a min-heap) and relax its edges. A settled vertex can never improve, because any other way to it would be at least as long. Skip heap entries that are out of date.
The problem
Given an undirected graph with non-negative weights and a source, return the shortest distance to every vertex, or -1
if it cannot be reached. Vertices are numbered from 0 and each edge is [u, v, weight].
Think first
- Which vertex's distance is certainly final?
- What does relaxing an edge mean?
- Why can a heap hold old entries?
Hints
Brute force, and why it fails
Repeatedly scan for the closest unsettled vertex: O(V²), which is fine for dense graphs.
The key insight
A min-heap finds the next vertex to settle in O(log V), giving O(E log V) overall.
Dry run
| dist | - - 0 |
|---|
Edges 0-1 (1), 0-2 (6), 1-2 (3); source 2. dist[2] = 0.
The plan
dist[src] = 0; heap = [(0, src)]
while heap: (d, u) = pop; if d > dist[u]: skip
for (v, w): if d + w < dist[v]: dist[v] = d + w; push
Complexity
- Time
O(E log V)- Space
O(V + E)
Each edge may push one heap entry.
Edge cases
- Unreachable vertices: -1.
- Zero-weight edges.
- A single vertex.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> dijkstra(int n, int[][] edges, int src) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(new int[]{e[1], e[2]}); adj.get(e[1]).add(new int[]{e[0], e[2]}); }
long[] dist = new long[n];
Arrays.fill(dist, Long.MAX_VALUE);
dist[src] = 0;
PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0])); // {distance, vertex}
pq.add(new long[]{0, src});
while (!pq.isEmpty()) {
long[] top = pq.poll();
int u = (int) top[1];
if (top[0] > dist[u]) continue; // an old, longer entry
for (int[] e : adj.get(u)) {
if (dist[u] + e[1] < dist[e[0]]) { // a shorter way to e[0] through u
dist[e[0]] = dist[u] + e[1];
pq.add(new long[]{dist[e[0]], e[0]});
}
}
}
List<Integer> out = new ArrayList<>();
for (long d : dist) out.add(d == Long.MAX_VALUE ? -1 : (int) d);
return out;
}
}C++
class Solution {
public:
vector<int> dijkstra(int n, vector<vector<int>>& edges, int src) {
vector<vector<pair<int, int>>> adj(n);
for (const vector<int>& e : edges) { adj[e[0]].push_back(make_pair(e[1], e[2])); adj[e[1]].push_back(make_pair(e[0], e[2])); }
vector<long long> dist(n, LLONG_MAX);
dist[src] = 0;
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq; // {dist, vertex}
pq.push(make_pair(0LL, src));
while (!pq.empty()) {
pair<long long, int> top = pq.top();
pq.pop();
int u = top.second;
if (top.first > dist[u]) continue; // an old, longer entry
for (const pair<int, int>& e : adj[u]) {
if (dist[u] + e.second < dist[e.first]) { // a shorter way to e.first through u
dist[e.first] = dist[u] + e.second;
pq.push(make_pair(dist[e.first], e.first));
}
}
}
vector<int> out;
for (long long d : dist) out.push_back(d == LLONG_MAX ? -1 : static_cast<int>(d));
return out;
}
};Python
import heapq
class Solution:
def dijkstra(self, n: int, edges: list[list[int]], src: int) -> list[int]:
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
dist = [float("inf")] * n
dist[src] = 0
pq = [(0, src)] # (distance, vertex)
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # an old, longer entry
for v, w in adj[u]:
if d + w < dist[v]: # a shorter way to v through u
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
return [-1 if d == float("inf") else d for d in dist]Common mistakes
- Using it with negative weights.
- Not skipping stale entries, which slows it down a lot.