Skip to content

Commit bacc47c

Browse files
authored
Update travelling_salesman_problem.py
1 parent 90d830a commit bacc47c

File tree

1 file changed

+21
-22
lines changed

1 file changed

+21
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,49 @@
11
#!/usr/bin/env python3
2-
from functools import lru_cache
32

3+
from functools import lru_cache
44

55
def tsp(distances: list[list[int]]) -> int:
66
"""
7-
Solves the Travelling Salesman Problem (TSP) using
8-
dynamic programming and bitmasking.
9-
Args:
10-
distances: 2D list where distances[i][j] is the
11-
distance between city i and city j.
12-
Returns:
13-
Minimum cost to complete the
14-
tour visiting all cities.
15-
Raises:
16-
ValueError: If any distance is negative.
17-
18-
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
19-
80
20-
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
21-
69
22-
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
7+
Solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.
8+
9+
Args:
10+
distances: 2D list where distances[i][j] is the distance between city i and city j.
11+
12+
Returns:
13+
Minimum cost to complete the tour visiting all cities.
14+
15+
Raises:
16+
ValueError: If any distance is negative.
17+
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
18+
80
19+
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
20+
69
21+
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
22+
Traceback (most recent call last):
23+
...
2324
ValueError: Distance cannot be negative
2425
"""
2526
n = len(distances)
2627
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
2728
raise ValueError("Distance cannot be negative")
29+
2830
visited_all = (1 << n) - 1
2931

3032
@lru_cache(None)
3133
def visit(city: int, mask: int) -> int:
3234
"""Recursively calculates the minimum cost to visit all cities."""
3335
if mask == visited_all:
3436
return distances[city][0] # Return to start
35-
min_cost = float("inf") # Large value to compare against
37+
38+
min_cost = float('inf') # Large value to compare against
3639
for next_city in range(n):
3740
if not mask & (1 << next_city): # If unvisited
3841
new_cost = distances[city][next_city] + visit(
3942
next_city, mask | (1 << next_city)
4043
)
4144
min_cost = min(min_cost, new_cost)
4245
return int(min_cost) # Ensure returning an integer
43-
4446
return visit(0, 1) # Start from city 0 with city 0 visited
45-
46-
4747
if __name__ == "__main__":
4848
import doctest
49-
5049
doctest.testmod()

0 commit comments

Comments
 (0)