Graph Algorithms

One small directed graph, with and without a cycle. Watch breadth-first and depth-first spread differently, catch the edge that closes a cycle, and follow Dijkstra settling the cheapest route.

ABCDEFGH
In the queue
  1. A
Visit order

Nothing yet.

  • Not reached
  • Waiting
  • Current
  • Finished
Speed

Step 1 of 20

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

Counters

Visited
0/8
In the queue
1
Nodes
8
Edges
10

Settings

Algorithm
Graph

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 detectionDoes a cycle exist, 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

V is the node count and E the edge count. Switch the graph to Has a cycle and the topological sort will get stuck - that is the connection between the two.