All problems
Hamiltonian Path Check
Problem
Decide whether an undirected graph with n nodes contains a Hamiltonian path: a path that visits every node exactly once.
Use backtracking from every possible start node, pruning with visited sets. edges is a list of [u, v] pairs and n is small.
Hint
A node of degree 1 must be an endpoint of any Hamiltonian path.
Test cases
case 1
in: [4,[[0,1],[1,2],[2,3]]]
expected: true
case 2
in: [4,[[0,1],[0,2],[0,3]]]
expected: false
case 3
in: [5,[[0,1],[1,2],[2,3],[3,4],[4,0]]]
expected: true
case 4
in: [4,[[0,1],[2,3]]]
expected: false
case 5
in: [1,[]]
expected: true
Starter codePython
def has_hamiltonian_path(n, edges):
# Your code here
pass5 test cases · run your code against them in the editor