Graph Algorithms

Dijkstra's Shortest Path Algorithm

4258362435A0B∞C∞D∞E∞F∞G∞H∞
Reached, not settled

Empty.

Settled, cheapest first

Nothing yet.

  • Not reached
  • Waiting
  • Current
  • Finished
1/20

A is 0 away from itself. Everything else starts at infinity.

Settings

Graph
More options

Dijkstra

  1. 1dist[start] = 0, everything else inf
  2. 2while unsettled nodes remain:
  3. 3 node = closest unsettled node
  4. 4 settle(node)
  5. 5 for each neighbour:
  6. 6 d = dist[node] + weight
  7. 7 if d < dist[neighbour]:
  8. 8 dist[neighbour] = d

What Each One Answers

AlgorithmWhat it answersTimeNeeds
Breadth-FirstFewest hops from the startO(V + E)A queue
Depth-FirstReachability, one branch at a timeO(V + E)A stack
Cycle DetectionWhether there is a cycle, and whereO(V + E)Node colours
Topological SortA valid order to do the work inO(V + E)No cycles
DijkstraCheapest path by edge weightO(E log V)Non-negative weights

Scroll the table sideways for the rest of the columns.

V is the number of nodes and E the number of edges. On the graph with a cycle, topological sort gets stuck, because a cycle leaves no valid order.