How Dijkstra’s algorithm works
Every distance starts at infinity except the source, which is 0. Repeatedly pick the unvisited vertex with the smallest distance, mark it visited, and relax each of its edges: if going through it is cheaper than the neighbour’s current distance, update the distance and remember the parent. Stop when every reachable vertex has been visited.
The example graph has five vertices, and 999 stands in for infinity. From A, the route A → C → E costs 12 at first; it is beaten later by A → B → D → E, which costs 11.
What to watch for when it runs
- The distance table changes only when a cheaper route is found — watch E drop from 12 to 11.
- The vertex chosen each round is the cheapest unvisited one, not the one with the fewest edges.
- This version finds that vertex with a plain loop; production code uses a priority queue.
Time and space complexity
- Time
- O(V²) as written, O((V + E) log V) with a heap
- Space
- O(V)
The scan for the minimum is what makes this version quadratic. A binary heap makes each pick O(log V). Negative edge weights break the algorithm; Bellman-Ford handles them.