Skip to content

Commit be956ab

Browse files
authored
Update travelling_salesman_problem.py
1 parent 006a79e commit be956ab

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
11
#!/usr/bin/env python3
22

3-
43
def tsp(distances: list[list[int]]) -> int:
54
"""
65
Solves the Travelling Salesman Problem (TSP)
76
using dynamic programming and bitmasking.
8-
97
Args:
108
distances: 2D list where distances[i][j]
119
is the distance between city i and city j.
12-
1310
Returns:
14-
Minimum cost to complete the tour visiting all cities.
15-
11+
Minimum cost to complete the
12+
tour visiting all cities.
1613
Raises:
1714
ValueError: If any distance is negative.
1815
@@ -31,18 +28,17 @@ def tsp(distances: list[list[int]]) -> int:
3128
n = len(distances)
3229
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
3330
raise ValueError("Distance cannot be negative")
34-
3531
# Memoization table
3632
memo = [[-1] * (1 << n) for _ in range(n)]
3733
visited_all = (1 << n) - 1 # All cities visited mask
38-
3934
def visit(city: int, mask: int) -> int:
4035
"""Recursively calculates the minimum cost to visit all cities."""
4136
if mask == visited_all:
4237
return distances[city][0] # Return to the starting city
38+
4339
if memo[city][mask] != -1: # Return cached result if exists
4440
return memo[city][mask]
45-
min_cost = float("inf") # Use infinity for initial comparison
41+
min_cost = float('inf') # Use infinity for initial comparison
4642
for next_city in range(n):
4743
if not (mask & (1 << next_city)): # If unvisited
4844
new_cost = distances[city][next_city] + visit(
@@ -51,11 +47,10 @@ def visit(city: int, mask: int) -> int:
5147
min_cost = min(min_cost, new_cost)
5248
memo[city][mask] = int(min_cost) # Store result as an integer
5349
return memo[city][mask] # Return the cached result
54-
5550
return visit(0, 1) # Start from city 0 with city 0 visited
56-
57-
5851
if __name__ == "__main__":
5952
import doctest
60-
61-
doctest.testmod()
53+
try:
54+
doctest.testmod()
55+
except Exception as e:
56+
print(f"An error occurred during doctest: {e}")

0 commit comments

Comments
 (0)