Dijkstra's Algorithm
–
Pseudocode
1dist[s] ← 0, every other dist ← ∞2while some vertex is not finished:3 u ← the unfinished vertex with the smallest dist4 if dist[u] = ∞: stop // the rest can't be reached5 mark u finished // its dist can't get smaller now6 for each edge u → v (weight w) to an unfinished v:7 if dist[u] + w < dist[v]:8 dist[v] ← dist[u] + w; prev[v] ← u
Finished
0
Updates
0
vertex being finished∞ → 7tentative distancefinished / shortest-path tree
What is Dijkstra's Algorithm?
Dijkstra's algorithm finds the shortest path from one start vertex to every other vertex in a graph whose edges have non-negative weights, like road lengths or travel times.
It keeps a tentative distance for every vertex. Each round it picks the unfinished vertex with the smallest tentative distance: that distance can never improve any more (any other route would have to go through a vertex that is already farther away), so the vertex is finished. Then it tries to improve its neighbours through it, which is called relaxing an edge.
Always finish the closest unfinished vertex, then relax its edges.
Using the Visualizer
- • Edit graph slides out the weighted matrix. Tick Directed for one-way roads. Pick the start or click a vertex.
- • Numbers next to the vertices are their current distances. Yellow = reached, green = finished.
- • A green edge being drawn is an improvement; a red dashed one is a route that wasn't shorter.
- • Type a negative weight and Dijkstra refuses: try the same graph on Bellman-Ford.
How It Works
1. Start
Distance 0 for the start, ∞ for everything else.
2. Pick the closest
Choose the unfinished vertex with the smallest distance and mark it finished.
3. Relax its edges
For each edge u → v of weight w: if dist[u] + w < dist[v], update dist[v] and set prev[v] = u.
4. Repeat
Until every reachable vertex is finished. The prev edges form the shortest-path tree.
Why no negative edges? Finishing the closest vertex assumes going further can only cost more. A negative edge breaks that: a longer detour could suddenly come out cheaper after the vertex was already finished.
Implementation
Properties & Complexity
Time Complexity
- • Array scan: O(V²), simplest and best for dense graphs
- • Binary heap: O((V + E) log V)
- • Fibonacci heap: O(E + V log V)
Space & Properties
- • Space: O(V) for dist, prev and the finished flags
- • Output: distances plus a shortest-path tree
- • Greedy: each vertex is finished exactly once
Where It Is Used
- • Maps and GPS: fastest route between places
- • Network routing: OSPF finds cheapest paths between routers
- • Games: path finding (A* is Dijkstra plus a hint)
- • Any "cheapest way" problem with non-negative costs
Limitations
- • Negative weights: gives wrong answers, use Bellman-Ford
- • One source: for all pairs, run it V times or use Floyd-Warshall
- • Explores everywhere: no sense of direction towards a target