Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -26,24 +26,20 @@ def held_karp_tsp(dist_matrix):
|
|
| 26 |
bits |= 1 << bit
|
| 27 |
for next_city in subset:
|
| 28 |
prev_bits = bits & ~(1 << next_city)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
continue
|
| 33 |
-
current_dist = memo[(prev_bits, k)] + dist_matrix[k][next_city]
|
| 34 |
-
if current_dist < min_dist:
|
| 35 |
-
min_dist = current_dist
|
| 36 |
-
memo[(bits, next_city)] = min_dist
|
| 37 |
|
| 38 |
# Find optimal tour
|
| 39 |
bits = (2 ** n - 1) - 1
|
| 40 |
min_tour_cost = inf
|
| 41 |
last_city = None
|
| 42 |
for k in range(1, n):
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
|
| 48 |
# Backtrack to find the full tour
|
| 49 |
tour = [0]
|
|
@@ -51,6 +47,8 @@ def held_karp_tsp(dist_matrix):
|
|
| 51 |
for _ in range(n - 1):
|
| 52 |
tour.append(last_city)
|
| 53 |
bits &= ~(1 << last_city)
|
|
|
|
|
|
|
| 54 |
next_city = min(
|
| 55 |
[(memo[(bits, k)] + dist_matrix[k][last_city], k) for k in range(n) if (bits, k) in memo],
|
| 56 |
key=lambda x: x[0],
|
|
|
|
| 26 |
bits |= 1 << bit
|
| 27 |
for next_city in subset:
|
| 28 |
prev_bits = bits & ~(1 << next_city)
|
| 29 |
+
if (prev_bits, next_city) in memo:
|
| 30 |
+
min_dist = memo[(prev_bits, next_city)] + dist_matrix[next_city][0]
|
| 31 |
+
memo[(bits, next_city)] = min_dist
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# Find optimal tour
|
| 34 |
bits = (2 ** n - 1) - 1
|
| 35 |
min_tour_cost = inf
|
| 36 |
last_city = None
|
| 37 |
for k in range(1, n):
|
| 38 |
+
if (bits, k) in memo:
|
| 39 |
+
tour_cost = memo[(bits, k)] + dist_matrix[k][0]
|
| 40 |
+
if tour_cost < min_tour_cost:
|
| 41 |
+
min_tour_cost = tour_cost
|
| 42 |
+
last_city = k
|
| 43 |
|
| 44 |
# Backtrack to find the full tour
|
| 45 |
tour = [0]
|
|
|
|
| 47 |
for _ in range(n - 1):
|
| 48 |
tour.append(last_city)
|
| 49 |
bits &= ~(1 << last_city)
|
| 50 |
+
if bits == 0:
|
| 51 |
+
break
|
| 52 |
next_city = min(
|
| 53 |
[(memo[(bits, k)] + dist_matrix[k][last_city], k) for k in range(n) if (bits, k) in memo],
|
| 54 |
key=lambda x: x[0],
|