Video in progress
When you write Dijkstra's algorithm with a PriorityQueue, how do you deal with the lack of decrease-key?
Java's PriorityQueue has no way to decrease a key, so when I find a new, shorter distance I add the node to the queue again. When I pull one out and its distance is larger than the one in dist, it's a stale entry and I skip it.
📖 Answer
record Edge(int to, int w) {}
static long[] dijkstra(List<List<Edge>> g, int src) {
long[] dist = new long[g.size()];
Arrays.fill(dist, Long.MAX_VALUE);
dist[src] = 0;
PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[1]));
pq.offer(new long[]{src, 0});
while (!pq.isEmpty()) {
long[] top = pq.poll();
int v = (int) top[0];
if (top[1] > dist[v]) continue; // stale entry
for (Edge e : g.get(v)) {
long nd = dist[v] + e.w();
if (nd < dist[e.to()]) {
dist[e.to()] = nd;
pq.offer(new long[]{e.to(), nd});
}
}
}
return dist;
}
This is "lazy deletion". The queue can grow up to E elements, and the complexity is O(E log E), which in practice is the same as O(E log V) because log E ≤ 2 log V.
There is a way to pq.remove(node) and re-add, but remove(Object) is O(n), which eats up the whole benefit.
An important limitation: with a negative-weight edge, Dijkstra gives a wrong answer, because it treats the distance of a node pulled from the queue as final. In that case you need Bellman-Ford.
One more practical point: putting a long[] into the queue is convenient, but it allocates an object on every call. On a graph with millions of edges, if GC pressure becomes noticeable, you write your own heap built on primitives.
Sign up to mark studied questions and save your progress.