Problem 437
Hamiltonian Path
Hard · 30 pts · Graph, Backtracking, Bitmask, Dynamic Programming
Problem
A Hamiltonian path visits every node of a graph exactly once, moving only along edges; it may start and end at any nodes. Decide whether the given undirected graph has one. The problem is NP-complete, but for up to 12 nodes a bitmask dynamic program works: dp[mask][v] is true if some path visits exactly the nodes in mask and ends at v.
Input
First line: N and M. Next M lines: an edge u v (nodes labelled 1 to N).
Output
Print YES if a Hamiltonian path exists, otherwise NO.
Constraints
1 <= N <= 12; 0 <= M <= N(N-1)/2
Example input
4 3 1 2 2 3 3 4
Example output
YES
Explanation
With edges 1-2, 2-3 and 3-4, the path 1 → 2 → 3 → 4 visits every node exactly once, so the answer is YES.