1 parent c685585 commit 16129e8Copy full SHA for 16129e8
1 file changed
algorithms/dynamic_programming/hamilton_cycle.py
@@ -0,0 +1,27 @@
1
+import functools
2
+
3
+def hamilton_cycle(graph, n):
4
+ height = 1 << n
5
6
+ dp = [[False for _ in range(n)] for _ in range(height)]
7
+ for i in range(n):
8
+ dp[1 << i][i] = True
9
10
+ for i in range(height):
11
+ ones, zeros = [], []
12
+ for pos in range(n):
13
+ if (1 << pos) & i:
14
+ ones.append(pos)
15
+ else:
16
+ zeros.append(pos)
17
18
+ for o in ones:
19
+ if not dp[i][o]:
20
+ continue
21
22
+ for z in zeros:
23
+ if graph[o][z]:
24
+ new_val = i + (1 << z)
25
+ dp[new_val][z] = True
26
27
+ return functools.reduce(lambda a, b: a or b, dp[height - 1])
0 commit comments