Hamiltonian path/circuit
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A Hamiltonian path visits every place exactly once, with no rule about using every road. Unlike the Euler case there is no quick test; it is a famously hard search, so it is worth knowing when a perfect tour is realistic and when to settle for good enough.
Practical use cases
- Web app: Tiffin or parcel round visiting each home once. A delivery app has 12 customers and wants a route visiting each exactly once. For a dozen stops the app can try routes with backtracking, dropping any partial route that gets stuck, and still answer in under a second.
- Web app: Tour planner for a sightseeing app. A trip app builds a day plan that visits each chosen attraction once. With 8 to 10 spots exhaustive search is fine, but for 30 spots the app switches to a quick approximate route and tells the user it is "good, not perfect", which is honest and still useful.
- Web app: Playlist or quiz ordering puzzles. A word-chain game needs an order using every card exactly once so that each pair fits. The game checks whether such a chain exists with backtracking search.
- System: Circuit boards and old DNA methods. Board designers route a drill through all holes once, and early DNA methods needed a path through all fragments. It is a reminder that visiting every place once looks similar to using every road once, but is far harder, and so people use clever shortcuts and approximations.
The story: Aarav's Tiffin Round
Aarav had a summer job delivering tiffins to five houses in the neighbourhood. His boss said: "Visit every house exactly once. No house twice, none missed." Aarav loved the challenge until he tried it, and kept getting stuck after four houses.
He made a map: houses as dots, lanes that exist between them as lines. He tried a route, reached a house whose neighbours were all visited, and had to step back and try another turn. After a few such retreats he found a route that visited all five houses once.
Mira told him something remarkable. "Remember the postman, who wanted every lane once? That was easy: just count the odd junctions. Your problem wants every house once, and for that nobody knows a quick rule. For big maps, computers have to try routes and back up, and it can take a very long time."
Such a route is a Hamiltonian path. If it can also return to the first house along a lane, it is a Hamiltonian circuit. It sits close to the famous Travelling Salesman problem, and the usual method is backtracking: extend the route, and if you hit a dead end, undo the last step.
How to spot this problem, and where you need it
You must visit every item exactly once in a single tour, and the number of possible orders grows explosively with each extra stop.
Signs you need it
- The wording is "visit every node exactly once" or "tour of all places", not "use every road".
- Adding one more stop makes your search take many times longer.
- No easy counting trick exists, and every approach you try feels like trying all orders.
Where to use it in a project
- Small route planners for 10 or so stops, such as tiffin, courier or sightseeing tours.
- Puzzle and game features, such as word chains and board tours, with small inputs.
The solution
Use backtracking: start from a node, move to an unvisited neighbour, and continue. If you reach a point where all neighbours are used and not everything has been visited, step back and try the next neighbour. Stop when the path includes all nodes. Cut off early using simple checks, such as a node with no unvisited neighbours left. For large inputs, accept approximate answers instead.
Payoff: Before: trying all 479 million orders of 12 stops. After: smart pruning finds a route in a few thousand tries, instantly.
Explain it like I am 8
You must visit every classroom in the school exactly once, only walking along the corridors. You try a path; if you get stuck in a classroom whose corridors all lead to rooms you have already seen, you go back one room and try another corridor.
How it works, step by step
- Start at some node and put it in the route. Mark it visited.
- Look at each neighbour that is not visited yet and try to extend the route there.
- If the route now contains all nodes, you found a Hamiltonian path.
- If you reach a node with no unvisited neighbours before covering everyone, backtrack: remove it from the route and try the next option.
- For a circuit, also check that the last node has a lane back to the first. If all starts fail, no such route exists.
The code in four languages
PHP
<?php
// Hamiltonian path by backtracking: visit every node exactly once
function hamiltonianPath(array $adj, int $start): ?array {
$n = count($adj);
$path = [$start];
$visited = array_fill(0, $n, false);
$visited[$start] = true;
$extend = function () use (&$extend, &$path, &$visited, $adj, $n): bool {
if (count($path) === $n) return true; // every house covered
$u = $path[count($path) - 1];
foreach ($adj[$u] as $v) {
if ($visited[$v]) continue;
$visited[$v] = true; // try going to v
$path[] = $v;
if ($extend()) return true;
array_pop($path); // dead end: backtrack
$visited[$v] = false;
}
return false;
};
return $extend() ? $path : null;
}
// houses A..E = 0..4, neighbours in the order we try them
$adj = [[3, 1], [0, 2], [1, 3, 4], [0, 2, 4], [2, 3]];
$path = hamiltonianPath($adj, 0);
echo 'Route: ' . ($path ? implode(' -> ', $path) : 'none') . PHP_EOL;
// a star has no such route: the middle node cannot be passed twice
$star = [[1, 2, 3], [0], [0], [0]];
echo 'Star: ' . (hamiltonianPath($star, 1) ? 'found' : 'none') . PHP_EOL;JavaScript
// Hamiltonian path by backtracking: visit every node exactly once
function hamiltonianPath(adj, start) {
const n = adj.length;
const path = [start];
const visited = new Array(n).fill(false);
visited[start] = true;
function extend() {
if (path.length === n) return true; // every house covered
const u = path[path.length - 1];
for (const v of adj[u]) {
if (visited[v]) continue;
visited[v] = true; // try going to v
path.push(v);
if (extend()) return true;
path.pop(); // dead end: backtrack
visited[v] = false;
}
return false;
}
return extend() ? path : null;
}
// houses A..E = 0..4, neighbours in the order we try them
const adj = [[3, 1], [0, 2], [1, 3, 4], [0, 2, 4], [2, 3]];
const path = hamiltonianPath(adj, 0);
console.log('Route: ' + (path ? path.join(' -> ') : 'none'));
// a star has no such route: the middle node cannot be passed twice
const star = [[1, 2, 3], [0], [0], [0]];
console.log('Star: ' + (hamiltonianPath(star, 1) ? 'found' : 'none'));Java
import java.util.*;
public class Main {
// Hamiltonian path by backtracking: visit every node exactly once
static List<Integer> hamiltonianPath(int[][] adj, int start) {
int n = adj.length;
List<Integer> path = new ArrayList<>(List.of(start));
boolean[] visited = new boolean[n];
visited[start] = true;
return extend(adj, path, visited) ? path : null;
}
static boolean extend(int[][] adj, List<Integer> path, boolean[] visited) {
if (path.size() == adj.length) return true; // every house covered
int u = path.get(path.size() - 1);
for (int v : adj[u]) {
if (visited[v]) continue;
visited[v] = true; // try going to v
path.add(v);
if (extend(adj, path, visited)) return true;
path.remove(path.size() - 1); // dead end: backtrack
visited[v] = false;
}
return false;
}
public static void main(String[] args) {
// houses A..E = 0..4, neighbours in the order we try them
int[][] adj = {{3, 1}, {0, 2}, {1, 3, 4}, {0, 2, 4}, {2, 3}};
List<Integer> path = hamiltonianPath(adj, 0);
String route = "none";
if (path != null) {
List<String> words = new ArrayList<>();
for (int x : path) words.add(String.valueOf(x));
route = String.join(" -> ", words);
}
System.out.println("Route: " + route);
// a star has no such route: the middle node cannot be passed twice
int[][] star = {{1, 2, 3}, {0}, {0}, {0}};
System.out.println("Star: " + (hamiltonianPath(star, 1) != null ? "found" : "none"));
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// hamiltonianPath uses backtracking: visit every node exactly once.
func hamiltonianPath(adj [][]int, start int) ([]int, bool) {
n := len(adj)
path := []int{start}
visited := make([]bool, n)
visited[start] = true
var extend func() bool
extend = func() bool {
if len(path) == n {
return true // every house covered
}
u := path[len(path)-1]
for _, v := range adj[u] {
if visited[v] {
continue
}
visited[v] = true // try going to v
path = append(path, v)
if extend() {
return true
}
path = path[:len(path)-1] // dead end: backtrack
visited[v] = false
}
return false
}
if extend() {
return path, true
}
return nil, false
}
func main() {
// houses A..E = 0..4, neighbours in the order we try them
adj := [][]int{{3, 1}, {0, 2}, {1, 3, 4}, {0, 2, 4}, {2, 3}}
route := "none"
if path, ok := hamiltonianPath(adj, 0); ok {
words := make([]string, len(path))
for i, x := range path {
words[i] = strconv.Itoa(x)
}
route = strings.Join(words, " -> ")
}
fmt.Println("Route: " + route)
// a star has no such route: the middle node cannot be passed twice
star := [][]int{{1, 2, 3}, {0}, {0}, {0}}
if _, ok := hamiltonianPath(star, 1); ok {
fmt.Println("Star: found")
} else {
fmt.Println("Star: none")
}
}Time: O(n!) in the worst case · Extra space: O(n). Backtracking may try almost every ordering of the nodes. No fast general solution is known; it is a famously hard (NP-complete) problem.
Watch out for
- Confusing it with the Euler path. Euler = every edge once (easy rule), Hamiltonian = every node once (hard).
- Forgetting to un-mark a node when backtracking, so later routes think it is still used.
- For a circuit, forgetting the final check that the last node connects back to the start.
Quick check
- A Hamiltonian path visits...
- Every edge exactly once
- Every node exactly once
- Every node at least twice
- Only the nodes on the shortest route
- What do we do when the route reaches a node with no unvisited neighbours (and not everyone is covered)?
- Backtrack and try another option
- Accept the route
- Restart from a random node
- Is there a simple degree-counting rule that decides if a Hamiltonian path exists?
- Yes, check for cycles
- Yes, count odd degrees
- No general quick rule is known