codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

53 / 65 topics
49Graph Coloring50Topological Sorting51Strongly Connected Components52Eulerian Cycles and Paths53Hamiltonian Cycles
Tutorials/Data Structures & Algorithms/Hamiltonian Cycles
🧮Data Structures & Algorithms

Hamiltonian Cycles

Updated 2026-04-20
3 min read

Introduction

In graph theory, a Hamiltonian Cycle is a cycle that visits each vertex exactly once and returns to the starting vertex. This problem is named after William Rowan Hamilton who introduced it in 1859. The challenge of finding a Hamiltonian Cycle lies in its NP-complete nature, meaning that there is no known polynomial-time algorithm for solving it efficiently for all cases.

This tutorial will explore the concept of Hamiltonian Cycles, their significance, and various algorithms used to detect them. We'll also discuss real-world applications and best practices when dealing with this problem.

Understanding Hamiltonian Cycles

Definition

A Hamiltonian Cycle in a graph \( G = (V, E) \) is a cycle that visits each vertex exactly once and returns to the starting vertex. Formally:

  • It is a sequence of vertices \( v_1, v_2, ..., v_n, v_1 \) such that:
    • Each vertex \( v_i \) appears exactly once in the sequence.
    • There is an edge between every pair of consecutive vertices \( (v_i, v_{i+1}) \).
    • The last vertex \( v_n \) has an edge to the first vertex \( v_1 \).

Properties

  • Hamiltonian Path: A path that visits each vertex exactly once but does not necessarily return to the starting vertex.
  • Complete Graph: Every pair of distinct vertices is connected by a unique edge. In a complete graph with \( n \) vertices, there are \( (n-1)!/2 \) Hamiltonian cycles.

Algorithms for Finding Hamiltonian Cycles

Brute Force Approach

The simplest approach to finding a Hamiltonian Cycle involves checking all possible permutations of the vertices:

function isHamiltonianCycle(graph, path) {
    const n = graph.length;
    if (path.length !== n || !graph[path[0]][path[n - 1]]) return false;

    for (let i = 0; i < n - 1; i++) {
        if (!graph[path[i]][path[i + 1]]) return false;
    }

    const visited = new Set();
    for (const vertex of path) {
        if (visited.has(vertex)) return false;
        visited.add(vertex);
    }
    return true;
}

function findHamiltonianCycle(graph) {
    const n = graph.length;
    const vertices = Array.from({ length: n }, (_, i) => i);

    function permute(arr, m = []) {
        if (arr.length === 0) {
            if (isHamiltonianCycle(graph, [...m, m[0]])) {
                return [m];
            }
            return [];
        } else {
            let results = [];
            for (let i = 0; i < arr.length; i++) {
                const curr = arr.slice();
                const next = curr.splice(i, 1);
                results.push(...permute(curr.slice(), m.concat(next)));
            }
            return results;
        }
    }

    return permute(vertices.slice(1));
}

Complexity: \( O(n!) \)

Backtracking Approach

Backtracking is a more efficient approach that builds the Hamiltonian Cycle incrementally and backtracks when it finds an invalid configuration:

function backtrack(graph, path) {
    const n = graph.length;
    if (path.length === n && graph[path[n - 1]][path[0]]) return [path];

    let cycles = [];
    for (let v = 0; v < n; v++) {
        if (!graph[path[path.length - 1]][v] || path.includes(v)) continue;

        const newPath = [...path, v];
        const result = backtrack(graph, newPath);
        if (result.length > 0) cycles.push(result[0]);
    }
    return cycles;
}

function findHamiltonianCycleBacktracking(graph) {
    for (let startVertex = 0; startVertex < graph.length; startVertex++) {
        const cycle = backtrack(graph, [startVertex]);
        if (cycle.length > 0) return cycle;
    }
    return [];
}

Complexity: \( O(n!) \)

Approximation Algorithms

For large graphs where exact solutions are impractical, approximation algorithms can be used to find near-optimal Hamiltonian Cycles. One such algorithm is the Nearest Neighbor Heuristic:

function nearestNeighbor(graph) {
    const n = graph.length;
    let path = [0];
    let visited = new Set([0]);

    while (path.length < n) {
        let nextVertex = -1;
        let minDistance = Infinity;

        for (let v = 0; v < n; v++) {
            if (!visited.has(v) && graph[path[path.length - 1]][v] < minDistance) {
                minDistance = graph[path[path.length - 1]][v];
                nextVertex = v;
            }
        }

        path.push(nextVertex);
        visited.add(nextVertex);
    }

    // Connect the last vertex to the first to form a cycle
    if (graph[path[n - 1]][path[0]]) {
        return [...path, path[0]];
    } else {
        return [];
    }
}

Complexity: \( O(n^2) \)

Real-World Applications

Hamiltonian Cycles have numerous applications in various fields:

  • Computer Networks: Routing packets in a network to ensure all nodes are visited.
  • Scheduling Problems: Optimizing job schedules to visit all tasks exactly once.
  • Traveling Salesman Problem (TSP): Finding the shortest possible route that visits each city exactly once and returns to the origin city.

Best Practices

  1. Understand Graph Properties: For sparse graphs, backtracking or approximation algorithms might be more efficient than brute force.
  2. Use Efficient Data Structures: Utilize adjacency lists for sparse graphs and adjacency matrices for dense graphs.
  3. Optimize with Heuristics: For large-scale problems, consider using heuristic-based methods like the nearest neighbor algorithm.

Conclusion

Hamiltonian Cycles are a fundamental concept in graph theory with significant implications in various fields. While finding an exact solution is computationally expensive, understanding different algorithms and their trade-offs can help in selecting the most appropriate approach for specific use cases. By leveraging efficient data structures and optimization techniques, developers can effectively solve problems involving Hamiltonian Cycles.


This comprehensive tutorial provides a detailed exploration of Hamiltonian Cycles, including definitions, properties, algorithms, real-world applications, and best practices.


PreviousEulerian Cycles and PathsNext Network Flow Problems

Recommended Gear

Eulerian Cycles and PathsNetwork Flow Problems