Dijkstra
Dijkstra's algorithm finds shortest paths from a source on a graph with non-negative edge weights. A min-heap always expands the closest unsettled node. Negative weights make it incorrect.
Detailed Explanation
BFS treats every edge as length 1. When edges have different lengths, the first time you reach a node may not be the cheapest. Dijkstra restores a "closest first" order. Each node holds a tentative distance, initially infinity except the source at 0. A priority queue pops the node with the smallest tentative distance. You then relax its edges: if going through this node improves a neighbour, update that neighbour and push it.
Because weights are non-negative, the first time a node is popped as the closest remaining node, its distance is final. You can skip later heap entries for that node (the "stale heap" style common in Java: push a new pair instead of decrease-key). If you see a popped distance worse than the recorded one, ignore it.
Java has no pairing-heap decrease-key on PriorityQueue. The stale-entry approach uses int[] plus record Node(int id, long dist) in the heap. Worst-case extra heap entries are fine for typical contest and interview sizes.
You reach for Dijkstra on maps, routing, and any non-negative weighted shortest path. You reach for BFS when every edge is 1. You reach for Bellman-Ford when weights can be negative (and to detect negative cycles). You reach for a topological relax when the graph is a DAG.
The cost is O((V + E) log V) with a binary heap. The cost of using int for distances is overflow; use long and a sentinel like Long.MAX_VALUE / 4. The cost of negative edges is a wrong answer, not an exception. The cost of an adjacency list of int[][] vs a map is implementation detail; lists of (to, weight) pairs are enough.
Disconnected nodes stay at infinity. If the graph is undirected, add both directions. If it is directed, do not.
Code Examples
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class Dijkstra {
record Edge(int to, int w) {}
record Node(int id, long dist) {}
static long[] dist(int n, List<List<Edge>> g, int src) {
long[] d = new long[n];
Arrays.fill(d, Long.MAX_VALUE / 4);
d[src] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>((a, b) -> Long.compare(a.dist, b.dist));
pq.add(new Node(src, 0));
while (!pq.isEmpty()) {
Node cur = pq.poll();
if (cur.dist != d[cur.id]) {
continue; // stale heap entry
}
for (Edge e : g.get(cur.id)) {
long nd = cur.dist + e.w;
if (nd < d[e.to]) {
d[e.to] = nd;
pq.add(new Node(e.to, nd));
}
}
}
return d;
}
public static void main(String[] args) {
List<List<Edge>> g = new ArrayList<>();
for (int i = 0; i < 3; i++) {
g.add(new ArrayList<>());
}
g.get(0).add(new Edge(1, 2));
g.get(0).add(new Edge(2, 5));
g.get(1).add(new Edge(2, 1));
System.out.println(dist(3, g, 0)[2]); // prints: 3
}
}Common Gotchas
Negative weights break the algorithm
a later cheaper path can exist after you finalized a node.
`int` distances overflow
use `long` and a large sentinel, not `Integer.MAX_VALUE + weight`.
Stale heap entries are normal
compare popped distance to `d[id]` before relaxing.