Skip to content

Commit 25a33e9

Browse files
author
Hamid Gasmi
committed
#150 is completed with an DP exact algorithm
1 parent 3eadd0b commit 25a33e9

File tree

4 files changed

+41
-32
lines changed

4 files changed

+41
-32
lines changed

4-np-complete-problems/2-coping_with_np_completeness/travelling_salesman_school_bus.py

+17-32
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,7 @@
3535
# ... So, to loop on all possible vertices, we just need to loop s from 1 to 2**n - 1
3636
def shortest_path(w, S, C):
3737

38-
#print("C: ", C)
39-
#print("S, C[S]: ", S, C[S])
40-
41-
shortest_path_length = INF
38+
shortest_path_length = INF
4239
for i in C[S]:
4340
if C[S][i] + w[i][0] >= shortest_path_length:
4441
continue
@@ -47,29 +44,26 @@ def shortest_path(w, S, C):
4744
if shortest_path_length == INF:
4845
return -1, []
4946

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
5153
while S > 0:
52-
prev_v = 0
53-
curr_v = -1
54-
path_length = INF
54+
5555
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
6158

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
7065

71-
shortest_path.append(1)
72-
return shortest_path_length, shortest_path[::-1]
66+
return shortest_path_length, shortest_path
7367

7468
def optimal_path(w):
7569

@@ -119,16 +113,7 @@ def optimal_path(w):
119113
v_j = map_v_bit_position[j]
120114
C_S[v_i] = min(C_S[v_i], C_S_minus_i[v_j] + w[v_j][v_i])
121115
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]
130116

131-
#print(path_length)
132117
return shortest_path(w, S, C)
133118

134119
def optimal_path_naive(graph):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
5 10
2+
1 2 5
3+
1 3 1
4+
1 4 3
5+
1 5 2
6+
2 3 2
7+
2 4 3
8+
2 5 1
9+
3 4 2
10+
3 5 3
11+
4 5 4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
4 6
2+
1 2 1
3+
1 3 1
4+
1 4 10
5+
2 3 5
6+
2 4 2
7+
3 4 3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
4 5
2+
1 2 1
3+
2 3 4
4+
3 4 5
5+
4 2 1
6+
1 4 10

0 commit comments

Comments
 (0)