Algorithms · Visualized
Hamiltonian Path
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
A Hamiltonian path visits every vertex of a graph exactly once. Time: O(n!) worst case average, O(n!) — NP-complete worst; space: O(n) — path and visited tracking.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Hamiltonian Path
BacktrackingA Hamiltonian path visits every vertex of a graph exactly once. Finding one uses backtracking: extend a partial path with an unvisited neighbor and back off whenever a dead end is reached before all vertices are covered.
How Hamiltonian Path Works
- Start the path at a vertex (here: vertex 0) and mark it visited.
- From the current end of the path, try each unvisited neighbor as the next step.
- If a neighbor is adjacent and unvisited, append it to the path, mark it visited, and recurse.
- If the path covers all vertices, a Hamiltonian path is found — stop.
- If a branch dead-ends before covering all vertices, remove the last vertex (backtrack) and try another neighbor.
Hamiltonian Path Worked Example
Input: Graph with edges 0–1, 1–2, 2–3, 3–0, 0–2
Path = [0], try neighbor 1 → [0,1]. From 1, try neighbor 2 → [0,1,2]. From 2, try neighbor 3 (the only unvisited one) → [0,1,2,3]. All 4 vertices covered → Hamiltonian path 0 → 1 → 2 → 3 found.
def hamiltonian(graph):
n = len(graph)
path = []
def rec(v):
path.append(v)
if len(path) == n:
return True
for nb in graph[v]:
if nb not in path and rec(nb):
return True
path.pop()
return False
for start in range(n):
if rec(start):
return path
return []Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Hamiltonian Path Time & Space Complexity
When to Use Hamiltonian Path
- Route planning that must visit every location exactly once.
- DNA fragment assembly modeling.
- Puzzle games like the Knight's Tour (a special case).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.