Graph Algorithms

Cycle Detection in a Directed Graph

ABCDEFGH
Grey, still on the path
  1. A
Black, finished

Nothing yet.

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

Colour A grey: it is on the path we are exploring.

Settings

Graph
More options

Cycle Detection

  1. 1colour[v] = white for all v
  2. 2
  3. 3visit(v):
  4. 4 colour[v] = grey
  5. 5 for each neighbour w:
  6. 6 if colour[w] == grey:
  7. 7 CYCLE - w is still on the path
  8. 8 if colour[w] == white: visit(w)
  9. 9 colour[v] = black

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.