Skip to content
← All questions

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 G=(V,E)G = (V, E), directed or undirected.
  • Positive edge lengths {lel_e : e∈Ee \in E}.
  • Source vertex s∈Vs \in V.
  • Output: dist(u) is the shortest distance from s to u for all reachable u.

Reasoning, step by step

  1. Initialize dist(u) = infinity and prev(u) = nil for all u in V.
  2. Set dist(s) = 0.
  3. Create priority queue H with all vertices, keyed by dist values.
  4. While H is not empty: extract min u from H.
  5. For each edge (u,v) in E: if dist(v) > dist(u) + l(u,v)l(u,v), then dist(v) = dist(u) + l(u,v)l(u,v), 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) + l(u,v)l(u,v): dist(v) = dist(u) + l(u,v)l(u,v)...'

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

Explore next

Answers are generated from source material and independently checked. Consult the original video or creator if something is unclear.