[prev] 95 [next]

Hamiltonian Path and Circuit (cont)

Algorithm for finding Hamiltonian path:

visited[] // array [0..nV-1] to keep track of visited vertices

hasHamiltonianPath(G,src,dest):
|  for all vertices v∈G do
|     visited[v]=false
|  end for
|  return hamiltonR(G,src,dest,#vertices(G)-1)

hamiltonR(G,v,dest,d):
|  Input G    graph
|        v    current vertex considered
|        dest destination vertex
|        d    distance "remaining" until path found
|
|  if v=dest then
|     if d=0 then return true else return false
|  else
|  |  mark v as visited
|  |  for each neighbour w of v in G do
|  |  |  if w has not been visited then
|  |  |     if hamiltonR(G,w,dest,d-1) then
|  |  |        return true
|  |  |     end if
|  |  |  end if
|  |  end for
|  end if
|  mark v as unvisited           // reset visited mark
|  return false