-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Hamiltonian_Cycle.py
112 lines (90 loc) · 2.59 KB
/
Hamiltonian_Cycle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""
Hamiltonian Path: a Hamiltonian path (or traceable path) is a path
in an undirected or directed graph that visits each vertex exactly
once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian
path that is a cycle.
Problem Link: https://en.wikipedia.org/wiki/Hamiltonian_path
Purpose: To determine the existance of a Hamiltonian Cycle in the provided
undirected graph and return the path if such path exist.
The nodes are numbered from 1 to N
Method : Backtracking
Time Complexity: O(2^N)
Space Complexity: O(N)
Argument : Graph (Dictionary)
Return : Hamiltonian Cycle (List)
"""
from collections import defaultdict
def Move_next_node(n, graph, pos, ans):
# Base Case: If all the node is visited:
if pos == n:
# Check wether the last node and the first node are
# connected in order to form a Cycle
if ans[0] in graph[ans[-1]]:
return ans + [ans[0]]
return False
current = ans[-1]
# Check for each of the adjoining vertices
for i in graph[current]:
# Check wether the node is already visited or not
if i not in ans:
ans += [i]
temp = Move_next_node(n, graph, pos + 1, ans)
if temp:
return temp
ans.pop()
return False
def Hamiltonial_Cycle(n, graph):
# To keep a track of already visited node and the answer
# We will start exploring the graph from Vertex 1
answer = [1]
# Start Exploring adjoining node/vertex
return Move_next_node(n, graph, 1, answer)
# ------------------------DRIVER CODE ------------------------
if __name__ == "__main__":
n, m = map(int, input("Enter the number of vertex and edges: ").split())
print("Enter the edges: ")
graph = defaultdict(list)
for i in range(m):
a, b = map(int, input().split())
graph[a] += [b]
graph[b] += [a]
ans = Hamiltonial_Cycle(n, graph)
if not ans:
print("Hamiltonian Cycle is not possible in the Given graph")
else:
print("Hamiltonian Cycle is possible in the graph")
print("The path is : ", *ans)
"""
Sample Input / Output
5----1------2
/\ \ /
/ \ \ /
/ \ \/
3------6-----4
Enter the number of vertex and edges: 6 8
Enter the edges
5 1
1 2
1 4
5 6
6 4
4 2
3 6
5 3
Hamiltonian Cycle is possible in the graph
The path is : 1 5 3 6 4 2 1
5----1------2
\ \
\ \
\ \
3------6-----4
Enter the number of vertex and edges: 6 6
Enter the edges:
5 1
3 6
6 4
1 2
5 6
1 4
Hamiltonian Cycle is not possible in the Given graph
"""