35
35
# ... So, to loop on all possible vertices, we just need to loop s from 1 to 2**n - 1
36
36
def shortest_path (w , S , C ):
37
37
38
- #print("C: ", C)
39
- #print("S, C[S]: ", S, C[S])
40
-
41
- shortest_path_length = INF
38
+ shortest_path_length = INF
42
39
for i in C [S ]:
43
40
if C [S ][i ] + w [i ][0 ] >= shortest_path_length :
44
41
continue
@@ -47,29 +44,26 @@ def shortest_path(w, S, C):
47
44
if shortest_path_length == INF :
48
45
return - 1 , []
49
46
50
- shortest_path = []
47
+ path_length = shortest_path_length
48
+ shortest_path = [- 1 ] * len (w [0 ])
49
+ shortest_path [0 ] = 1
50
+
51
+ prev_v = 0
52
+ pos = len (w [0 ]) - 1
51
53
while S > 0 :
52
- prev_v = 0
53
- curr_v = - 1
54
- path_length = INF
54
+
55
55
for i in C [S ]:
56
- if C [S ][i ] + w [i ][prev_v ] >= path_length :
57
- continue
58
-
59
- path_length = C [S ][i ] + w [i ][prev_v ]
60
- curr_v = i
56
+ if C [S ][i ] == path_length - w [i ][prev_v ]:
57
+ shortest_path [pos ] = i + 1
61
58
62
- if path_length == INF :
63
- break
64
-
65
- #print("C[S], curr_v, path_length: ", C[S], curr_v, path_length)
66
- shortest_path .append (curr_v + 1 )
67
- S = S ^ (1 << curr_v )
68
- prev_v = curr_v
69
- #print("S', path: ", S, shortest_path)
59
+ pos -= 1
60
+ path_length -= w [i ][prev_v ]
61
+ prev_v = i
62
+ S = S ^ (1 << i )
63
+
64
+ break
70
65
71
- shortest_path .append (1 )
72
- return shortest_path_length , shortest_path [::- 1 ]
66
+ return shortest_path_length , shortest_path
73
67
74
68
def optimal_path (w ):
75
69
@@ -119,16 +113,7 @@ def optimal_path(w):
119
113
v_j = map_v_bit_position [j ]
120
114
C_S [v_i ] = min (C_S [v_i ], C_S_minus_i [v_j ] + w [v_j ][v_i ])
121
115
j *= 2
122
- #print(C)
123
- #print(C[S])
124
- #path_length = INF
125
- #for i in C[S]:
126
- # if C[S][i] + w[i][1] >= path_length:
127
- # continue
128
-
129
- # path_length = C[S][i] + w[i][0]
130
116
131
- #print(path_length)
132
117
return shortest_path (w , S , C )
133
118
134
119
def optimal_path_naive (graph ):
0 commit comments