Graph Algorithms

Depth-First Search (DFS) on a Graph

ABCDEFGH
On the stack
  1. A
Visit order
  1. A
  • Not reached
  • Waiting
  • Current
  • Finished
1/20

Start at A. Depth-first follows one branch as far as it goes.

Settings

Graph
More options

Depth-First

  1. 1stack = [start]
  2. 2while stack:
  3. 3 node = stack.top
  4. 4 if node has an unseen neighbour:
  5. 5 mark it seen
  6. 6 stack.push(it)
  7. 7 else:
  8. 8 stack.pop() // done here

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.