Hamiltonian cycle algorithm using Backtracking technique.
Algorithm:
Algorithm NextValue(K)
{
repeat
{
x[k] := (x[k+1] mod (n+1));
if (x[k] = 0) then return;
if (G[x[k-1], x[k]] != 0) then
{
for j := 1 to k-1 do if (x[j] = x[k]) then break;
if (j = k) then
if ((k < n) or ((K = n) and G[x[n], x[l]] != 0))
then return;
}
}until false
}
Algorithm Hamiltonian(k)
{
repeat
{
NextValue(k);
if (x[k]=0) then return;
if (k=n) then write (x[1:n]);
else Hamiltonian(k + 1);
} until (false);
}
Source Code:
def hamiltonian_cycle(graph):
n = len(graph)
path = [-1] * n
def is_valid(v, k):
if graph[path[k-1]][v] == 0:
return False
if v in path[:k]:
return False
return True
def solve(k):
if k == n:
if graph[path[k-1]][path[0]] == 1:
return True
else:
return False
for v in range(1, n):
if is_valid(v, k):
path[k] = v
if solve(k+1):
return True
path[k] = -1
return False
path[0] = 0
if solve(1):
return path
else:
return None
graph = [[0, 1, 0, 1, 0],
[1, 0, 1, 1, 1],
[0, 1, 0, 0, 1],
[1, 1, 0, 0, 1],
[0, 1, 1, 1, 0]]
hamiltonian_cycle(graph)
Comments
Post a Comment