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

Backtracking

A 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

  1. Start the path at a vertex (here: vertex 0) and mark it visited.
  2. From the current end of the path, try each unvisited neighbor as the next step.
  3. If a neighbor is adjacent and unvisited, append it to the path, mark it visited, and recurse.
  4. If the path covers all vertices, a Hamiltonian path is found — stop.
  5. 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.

Python · Backtracking in Code
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

BestO(n) when found early
AverageO(n!) worst case
WorstO(n!) — NP-complete
SpaceO(n) — path and visited tracking

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.