Hamiltonian Cycle
Find a cycle in graph that visits each vertex exactly once and returns to starting vertex. NP-complete problem solved with backtracking.
Visualization
Interactive visualization for Hamiltonian Cycle
Interactive visualization with step-by-step execution
Implementation
1function hamiltonianCycle(graph: number[][]): number[] | null {
2 const n = graph.length;
3 const path: number[] = [-1];
4 path.length = n;
5 path[0] = 0;
6
7 function isSafe(v: number, pos: number): boolean {
8 if (graph[path[pos - 1]][v] === 0) return false;
9
10 for (let i = 0; i < pos; i++) {
11 if (path[i] === v) return false;
12 }
13
14 return true;
15 }
16
17 function hamCycleUtil(pos: number): boolean {
18 if (pos === n) {
19 return graph[path[pos - 1]][path[0]] === 1;
20 }
21
22 for (let v = 1; v < n; v++) {
23 if (isSafe(v, pos)) {
24 path[pos] = v;
25
26 if (hamCycleUtil(pos + 1)) return true;
27
28 path[pos] = -1;
29 }
30 }
31
32 return false;
33 }
34
35 return hamCycleUtil(1) ? path : null;
36}Deep Dive
Theoretical Foundation
NP-complete problem: find cycle visiting each vertex exactly once. Backtrack by trying each unvisited vertex, checking if edge exists. Must return to start vertex to complete cycle. Time: O(n!) in worst case.
Complexity
Time
O(n!)
O(n!)
O(n!)
Space
O(n)
Applications
Industry Use
Traveling Salesman Problem (TSP) foundation
Circuit board drilling optimization
DNA sequencing (finding Eulerian paths)
Network routing optimization
Game development (NPC patrol routes)
Logistics and delivery route planning
Manufacturing process optimization
Use Cases
Related Algorithms
N-Queens Problem
The N-Queens Problem asks: place N chess queens on an N×N chessboard so that no two queens threaten each other. This means no two queens can be on the same row, column, or diagonal. It's a classic constraint satisfaction problem that demonstrates backtracking, pruning, and systematic exploration of solution spaces. The problem has applications in parallel processing, resource allocation, and algorithm design education.
Sudoku Solver
Sudoku Solver uses backtracking to fill a 9×9 grid with digits 1-9, ensuring each row, column, and 3×3 box contains all digits exactly once. This classic constraint satisfaction problem demonstrates systematic exploration with constraint checking. The algorithm fills empty cells one by one, backtracking when constraints are violated, making it a perfect example of pruning in search algorithms.
Combination Sum
Find all unique combinations in array where chosen numbers sum to target. Numbers can be reused. Classic backtracking problem with pruning optimization.
Generate Valid Parentheses
Generate all combinations of n pairs of well-formed parentheses. Uses backtracking with constraint that closing parentheses never exceed opening ones.