Hamiltonian Cycle
A Hamiltonian cycle visits every vertex of a graph exactly once and returns to the start. Checking a proposed cycle is easy; finding one is NP-complete, so the standard method is backtracking.
Paths, Cycles and Why It Is Hard
- Hamiltonian path – a path that visits every vertex exactly once.
- Hamiltonian cycle – a Hamiltonian path whose last vertex is adjacent to its first, closed into a cycle.
- Hamiltonian graph – a graph that contains at least one Hamiltonian cycle.
A Hamiltonian cycle (or Hamiltonian circuit) in a graph with n vertices is a cycle v₁ → v₂ → … → vₙ → v₁ that uses every vertex exactly once. It uses exactly n edges. Every other edge in the graph is simply not used.
The name comes from William Rowan Hamilton's 1857 Icosian game, a puzzle about touring the 20 corners of a dodecahedron without revisiting any. The hero diagram shows the two outcomes that matter: on the left the path closes into a cycle; on the right, vertex P has only one edge, so the best possible is a Hamiltonian path.
The decision problem asks whether a given graph has a Hamiltonian cycle. It is one of Karp's original 21 NP-complete problems. A proposed cycle is checked in O(n) time, but no polynomial algorithm is known for finding one. See P, NP, NP-complete and NP-hard.
- Exactly n edges, each vertex entered once and left once
- Not every edge has to be used
- A degree-1 vertex rules out a cycle immediately
- Finding one is NP-complete; checking one is O(n)
Hamiltonian Cycle vs Euler Circuit
The two are easy to confuse in exams because both are tours of a graph. The difference is what must be covered exactly once: an Euler circuit covers every edge; a Hamiltonian cycle covers every vertex.
The difference in difficulty is dramatic. Euler's condition is simple and checkable in linear time: a connected graph has an Euler circuit exactly when every vertex has even degree. No such simple test exists for covering every vertex, which is exactly why the problem is NP-complete.
| Hamiltonian cycle | Euler circuit | |
|---|---|---|
| Covers exactly once | Every vertex | Every edge |
| Length | n edges | m edges (all of them) |
| Existence test | No simple rule; NP-complete | Connected and all degrees even |
| Time to decide | Exponential in the worst case | O(V + E) |
| Classic origin | Hamilton's Icosian game, 1857 | Königsberg bridges, 1736 |
- K4 has a Hamiltonian cycle but no Euler circuit: every degree is 3, which is odd
- The bowtie in the worked example has an Euler circuit (all degrees even) but no Hamiltonian cycle
- A plain 4-cycle has both: it is one loop through every vertex and every edge
Hamiltonian Cycle Using Backtracking
- Fix the start – put vertex 0 at position 0. Every cycle passes through it, so this removes n duplicate rotations.
- Try a candidate – for position k, try each vertex v adjacent to position k − 1.
- Check it is safe – v must not already be on the path.
- Recurse – place v and fill position k + 1.
- Close the cycle – when all n positions are filled, accept only if the last vertex is adjacent to vertex 0.
- Backtrack – if no candidate works, remove the last vertex, mark it unvisited, and return to the caller.
Backtracking builds the cycle one vertex at a time and abandons a partial path the moment it cannot be extended. It is exhaustive, so it is guaranteed to find a cycle if one exists, and to prove there is none if it returns empty-handed.
The safe-move check is what prunes the search: a vertex that is not adjacent to the current end, or already used, is never placed. A visited array makes that second test O(1) instead of scanning the path.
The tracer below runs this procedure on a 5-vertex graph. The first attempt builds a complete Hamiltonian path A → B → C → E → D, finds no edge back to A, and has to unwind three levels before the second attempt succeeds.
- Safe move: adjacent to the path's end and not yet visited
- The closing edge is checked only once all n vertices are placed
- Undo both the path entry and the visited flag on backtrack
- Stop at the first cycle for the decision question; continue to list them all
Terms, operations, and practical uses
Definitions
- Hamiltonian pathVisits every vertex exactly once; start and end may differ.
- Hamiltonian cycleA Hamiltonian path plus an edge back to the start.
- Hamiltonian graphA graph with at least one Hamiltonian cycle.
- Cut vertexA vertex whose removal disconnects the graph; it rules out a Hamiltonian cycle.
Theorems
- Dirac (1952)n ≥ 3 and every degree ≥ n/2 ⇒ Hamiltonian.
- Ore (1960)deg(u) + deg(v) ≥ n for all non-adjacent u, v ⇒ Hamiltonian.
- Karp (1972)Hamiltonian Cycle is NP-complete.
Related lessons
- BacktrackingThe choose, explore, undo pattern this search uses.
- Bitmask DPHeld–Karp's subset states for the O(2ⁿ·n²) algorithm.
- Depth-first searchThe traversal order the backtracking search follows.
- P, NP and NP-completeWhy no fast algorithm is expected.
Code in Python, C++ and Java
def hamiltonian_cycle(names, edges):
n = len(names)
index = {name: i for i, name in enumerate(names)}
adj = [[False] * n for _ in range(n)]
for u, v in edges:
adj[index[u]][index[v]] = adj[index[v]][index[u]] = True
# Any cycle passes through vertex 0, so fixing it as the start loses nothing.
path = [0]
visited = [False] * n
visited[0] = True
def extend():
if len(path) == n:
return adj[path[-1]][0] # the last vertex must lead back home
for v in range(n):
if adj[path[-1]][v] and not visited[v]:
path.append(v)
visited[v] = True
if extend():
return True
path.pop() # dead end: undo and try the next neighbour
visited[v] = False
return False
if not extend():
return None
return [names[i] for i in path + [0]]
def show(cycle):
return " -> ".join(cycle) if cycle else "no Hamiltonian cycle"
graph = ["AB", "AC", "BC", "BD", "BE", "CE", "DE"]
print("graph 1:", show(hamiltonian_cycle("ABCDE", graph)))
pendant = ["PQ", "QR", "RS", "ST", "TQ"]
print("graph 2:", show(hamiltonian_cycle("PQRST", pendant)))#include <iostream>
#include <string>
#include <vector>
using namespace std;
class HamiltonianCycle {
int n;
vector<vector<bool>> adj;
vector<int> path;
vector<bool> visited;
bool extend() {
if ((int)path.size() == n) return adj[path.back()][0]; // must lead back home
for (int v = 0; v < n; v++) {
if (adj[path.back()][v] && !visited[v]) {
path.push_back(v);
visited[v] = true;
if (extend()) return true;
path.pop_back(); // dead end: undo and try the next neighbour
visited[v] = false;
}
}
return false;
}
public:
string names;
HamiltonianCycle(const string& names, const vector<string>& edges)
: n(names.size()), adj(n, vector<bool>(n, false)), visited(n, false), names(names) {
for (const string& e : edges) {
int u = names.find(e[0]), v = names.find(e[1]);
adj[u][v] = adj[v][u] = true;
}
}
// Any cycle passes through vertex 0, so fixing it as the start loses nothing.
string solve() {
path = {0};
visited[0] = true;
if (!extend()) return "no Hamiltonian cycle";
string out;
for (int v : path) out += string(1, names[v]) + " -> ";
return out + names[0];
}
};
int main() {
HamiltonianCycle first("ABCDE", {"AB", "AC", "BC", "BD", "BE", "CE", "DE"});
cout << "graph 1: " << first.solve() << "\n";
HamiltonianCycle pendant("PQRST", {"PQ", "QR", "RS", "ST", "TQ"});
cout << "graph 2: " << pendant.solve() << "\n";
}import java.util.ArrayList;
import java.util.List;
public class Main {
static int n;
static boolean[][] adj;
static boolean[] visited;
static List<Integer> path;
static boolean extend() {
int last = path.get(path.size() - 1);
if (path.size() == n) return adj[last][0]; // must lead back home
for (int v = 0; v < n; v++) {
if (adj[last][v] && !visited[v]) {
path.add(v);
visited[v] = true;
if (extend()) return true;
path.remove(path.size() - 1); // dead end: undo and try the next neighbour
visited[v] = false;
}
}
return false;
}
static String hamiltonianCycle(String names, String[] edges) {
n = names.length();
adj = new boolean[n][n];
visited = new boolean[n];
for (String e : edges) {
int u = names.indexOf(e.charAt(0)), v = names.indexOf(e.charAt(1));
adj[u][v] = adj[v][u] = true;
}
// Any cycle passes through vertex 0, so fixing it as the start loses nothing.
path = new ArrayList<>(List.of(0));
visited[0] = true;
if (!extend()) return "no Hamiltonian cycle";
StringBuilder out = new StringBuilder();
for (int v : path) out.append(names.charAt(v)).append(" -> ");
return out.append(names.charAt(0)).toString();
}
public static void main(String[] args) {
String[] graph = {"AB", "AC", "BC", "BD", "BE", "CE", "DE"};
System.out.println("graph 1: " + hamiltonianCycle("ABCDE", graph));
String[] pendant = {"PQ", "QR", "RS", "ST", "TQ"};
System.out.println("graph 2: " + hamiltonianCycle("PQRST", pendant));
}
}Step through it
Running on A–B, A–C, B–C, B–D, B–E, C–E, D–E, start at A
Worked Example: Deciding by Hand With Graph Conditions
Before searching, a few structural facts often settle the question. An exam may ask you to justify an answer this way instead of tracing an algorithm.
- Graph 1 – a bowtie: triangles a–b–X and X–c–d sharing vertex X. n = 5.
- Graph 2 – K3,3: u₁, u₂, u₃ each joined to v₁, v₂, v₃. n = 6.
- Tools – two necessary conditions that can rule a cycle out, and two sufficient theorems that can guarantee one.
Graph 1. Vertex X is a cut vertex: removing it leaves {a, b} and {c, d} disconnected. A cycle through all the vertices stays connected after one vertex is removed, because what is left is a path. So the bowtie has no Hamiltonian cycle, although every vertex has degree at least 2. It does have a Hamiltonian path, a → b → X → c → d.
Graph 2. n = 6 and every vertex has degree 3 = n/2. Dirac's theorem (1952) says any simple graph with n ≥ 3 and every degree ≥ n/2 is Hamiltonian, so a cycle must exist. The figure shows one: u₁ → v₁ → … alternating sides, drawn in blue.
Notice the asymmetry. The conditions below can prove a cycle exists or prove it does not, but a graph can fail every test and still be Hamiltonian. A 5-vertex cycle C₅ has every degree 2 < 5/2 and is Hamiltonian anyway. When no test applies, you must search.
- Cut vertex or degree ≤ 1 ⇒ no Hamiltonian cycle
- Dirac (deg ≥ n/2) or Ore (deg u + deg v ≥ n) ⇒ a cycle exists
- Failing Dirac and Ore proves nothing: C₅ fails both and is Hamiltonian
- When no condition decides it, fall back to search
Time Complexity and Faster Exact Algorithms
Backtracking tries at most one ordering of the n − 1 remaining vertices per branch, so its worst case is O(n!). The safe-move check prunes heavily on sparse graphs, but no pruning rule prevents factorial growth in general. Space is O(n): the path, the visited array and the recursion stack.
The Held–Karp dynamic programme does better. The state dp[mask][v] records whether some path starting at vertex 0 visits exactly the vertices in mask and ends at v. There are 2ⁿ·n states and each has up to n transitions, so it runs in O(2ⁿ·n²) time and O(2ⁿ·n) space. At n = 20 that is about 4 × 10⁸ operations against 20! ≈ 2.4 × 10¹⁸. See bitmask dynamic programming.
Both are exponential, as expected for an NP-complete problem. For larger graphs practitioners use heuristics, or branch and bound on the related travelling salesman problem.
| Method | Time | Space | Practical limit |
|---|---|---|---|
| Brute force over all orderings | O(n!·n) | O(n) | n ≈ 10 |
| Backtracking with safe-move pruning | O(n!) worst | O(n) | n ≈ 20–30 on sparse graphs |
| Held–Karp bitmask DP | O(2ⁿ·n²) | O(2ⁿ·n) | n ≈ 20–25 |
- Verifying a given cycle: O(n)
- No polynomial algorithm is known, since the problem is NP-complete
Where These Tours Appear
Wherever a route must visit every location once, this cycle is the underlying object, and adding edge weights turns the question into the travelling salesman problem: find the cheapest Hamiltonian cycle.
Logistics and routing: delivery rounds, drilling holes in circuit boards, and robot arm paths. Puzzles: the knight's tour is a Hamiltonian path on the chessboard graph. Genome assembly: older overlap-graph assemblers look for a Hamiltonian path through the reads, one reason modern assemblers switched to de Bruijn graphs, which need only an Euler path. Gray codes: listing all n-bit strings so that neighbours differ in one bit is a Hamiltonian cycle on the hypercube.
- Weighted version = travelling salesman problem
- Knight's tour = Hamiltonian path on the knight's-move graph
- Gray codes = a tour of every corner of the n-cube
- Genome assembly moved from Hamiltonian paths to Euler paths for speed