Graph Algorithms

Breadth-First Search (BFS) on a Graph

ABCDEFGH
In the queue
  1. A
Visit order

Nothing yet.

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

Start at A. Breadth-first keeps a queue, so nearer nodes come out first.

Settings

Graph
More options

Breadth-First

  1. 1queue = [start]; seen = {start}
  2. 2while queue:
  3. 3 node = queue.shift()
  4. 4 for each neighbour:
  5. 5 if neighbour not in seen:
  6. 6 seen.add(neighbour)
  7. 7 queue.push(neighbour)

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.