A Hamiltonian path visits every vertex exactly once; a Hamiltonian cycle returns to the start. Deciding existence is NP-complete — in sharp contrast to Eulerian paths, which are linear-time.

The difference is instructive: “use every edge once” has a clean local characterisation (degree parity); “use every vertex once” has none.

Exact algorithms

Bitmask DP —

The standard approach for -.

// dp[mask][v] = can we visit exactly `mask` ending at v?
bool hamiltonianPath(int n, vector<vector<bool>>& adjm) {
    vector<vector<bool>> dp(1 << n, vector<bool>(n, false));
    for (int v = 0; v < n; v++) dp[1 << v][v] = true;
    for (int mask = 1; mask < (1 << n); mask++)
        for (int v = 0; v < n; v++) {
            if (!dp[mask][v]) continue;
            for (int u = 0; u < n; u++)
                if (!(mask >> u & 1) && adjm[v][u]) dp[mask | (1 << u)][u] = true;
        }
    for (int v = 0; v < n; v++) if (dp[(1 << n) - 1][v]) return true;
    return false;
}

Weighted, this is Held-Karp and solves TSP.

Counting, not just deciding

The inclusion-exclusion formula counts Hamiltonian paths in time and space (versus for the DP):

Walks are counted by a matrix power, so the memory is tiny. When and the DP’s memory does not fit, this is the fallback.

Sufficient conditions (for existence)

None of these are necessary, but each is easy to check:

TheoremCondition
Diracevery vertex has ⟹ Hamiltonian cycle ()
Ore for every non-adjacent pair ⟹ Hamiltonian cycle
Bondy-Chvátalclosure argument: repeatedly join non-adjacent pairs with sum ; is Hamiltonian iff its closure is
Tournamentsevery tournament has a Hamiltonian path (constructive: insertion sort on the vertices!)
Chvátal-Erdősconnectivity independence number ⟹ Hamiltonian

The tournament result is genuinely useful: in a tournament, a Hamiltonian path can be built in by inserting vertices one at a time into a growing path — literally insertion sort with “beats” as the comparison. A strongly connected tournament even has a Hamiltonian cycle.

Special graph classes

ClassHamiltonicity
Complete graphtrivially yes
TournamentHamiltonian path always exists
Grid graphpolynomial-time decidable (Itai-Papadimitriou-Szwarcfiter)
Interval graphpolynomial
Bipartite with no Hamiltonian cycle
Graph with a cut vertexno Hamiltonian cycle
TreeHamiltonian path iff it is a path
Cubic planarstill NP-complete

The bipartite parity check and the cut-vertex check are cheap necessary conditions worth applying before any expensive search.

For beyond the DP range, use branch and bound with strong pruning:

  • prune when a vertex of degree 0 remains in the unvisited set;
  • prune when the remaining graph becomes disconnected;
  • prune when two or more unvisited vertices have degree 1 in the remaining graph;
  • order candidates by fewest remaining options (Warnsdorff’s rule — this is what makes knight’s tours solvable on large boards almost instantly).

See also: Travelling Salesman · Held-Karp · Eulerian Path