Skip to main content

Hamiltonian Cycle

Definition​

The Hamiltonian Cycle Algorithm aims to find a cycle that visits every vertex in a graph exactly once and returns to the starting vertex. It's a problem of determining whether such a cycle exists in a given graph

Practice​

hamiltonianCycle(graph):
numVertices = graph.numVertices()
path = array of size numVertices
for each vertex in graph:
path[0] = vertex
if hamiltonianCycleUtil(graph, path, 1):
return path
return "No Hamiltonian cycle found"

hamiltonianCycleUtil(graph, path, pos):
if pos == graph.numVertices():
if graph.hasEdge(path[pos-1], path[0]):
return true
else:
return false
for v in graph.adjacentVertices(path[pos-1]):
if not isVisited(v, path, pos):
path[pos] = v
if hamiltonianCycleUtil(graph, path, pos+1):
return true
path[pos] = -1
return false

isVisited(vertex, path, pos):
for i from 0 to pos-1:
if path[i] == vertex:
return true
return false