What is the pseudocode for Dijkstra's algorithm?
The pseudocode initializes distances to infinity and predecessors to nil, sets the source distance to 0, and uses a priority queue H. It repeatedly extracts the vertex u with the minimum distance, relaxes all outgoing edges (u,v), updating dist(v) and prev(v) if a shorter path is found, and decreases the key of v in H.
Conditions
- Input: Graph , directed or undirected.
- Positive edge lengths { : }.
- Source vertex .
- Output: dist(u) is the shortest distance from s to u for all reachable u.
Reasoning, step by step
- Initialize dist(u) = infinity and prev(u) = nil for all u in V.
- Set dist(s) = 0.
- Create priority queue H with all vertices, keyed by dist values.
- While H is not empty: extract min u from H.
- For each edge (u,v) in E: if dist(v) > dist(u) + , then dist(v) = dist(u) + , prev(v) = u, and decreasekey(H, v).
Example
The video displays the full pseudocode: 'procedure dijkstra(G,l,s)... H = makequeue(V)... while H is not empty: u = deletemin(H)... if dist(v) > dist(u) + : dist(v) = dist(u) + ...'
Common misconceptions
- Forgetting to initialize the source distance to 0.
- Assuming the algorithm works with negative edge weights (the pseudocode specifies positive edge lengths).
- Not updating the priority queue key when a shorter path is found.
Watch the explanation
2:30 – 2:45Watch this moment ↗
Explore next
Answers are generated from source material and independently checked. Consult the original video or creator if something is unclear.