Skip to content
StackDecode
BacktrackingAnimated

Hamiltonian Cycle

Find a cycle through every node once by extending a path and backing up.

Time

O(n!)

Extra space

O(n)

Use it for

Tour finding on small graphs.

How it works

  1. A Hamiltonian cycle visits every node exactly once and returns to the start.
  2. Start at A. Extend the path to any unvisited neighbour.
  3. When all nodes are on the path, check whether the last node connects back to A.
  4. If a node has no unvisited neighbour (and the cycle is not complete), backtrack and try a different neighbour earlier on.

Watch it run

Loading animation…