Skip to content

Commit 7f43fa4

Browse files
authored
Update travelling_salesman_problem.py
1 parent d76d039 commit 7f43fa4

File tree

1 file changed

+5
-14
lines changed

1 file changed

+5
-14
lines changed

dynamic_programming/travelling_salesman_problem.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,28 @@
22

33
from functools import lru_cache
44

5-
65
def tsp(distances: list[list[int]]) -> int:
76
"""
8-
Solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.
9-
7+
Solves the Travelling Salesman Problem (TSP) using
8+
dynamic programming and bitmasking.
109
Args:
11-
distances: A 2D list where distances[i][j] represents the distance between city i and city j.
12-
10+
distances: A 2D list where distances[i][j] represents the
11+
distance between city i and city j.
1312
Returns:
1413
The minimum cost to complete the tour visiting all cities.
15-
1614
Raises:
1715
ValueError: If any distance is negative.
1816
1917
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
2018
80
2119
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
2220
69
23-
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]) # doctest: +ELLIPSIS
24-
Traceback (most recent call last):
25-
...
21+
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
2622
ValueError: Distance cannot be negative
2723
"""
2824
n = len(distances)
2925
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
3026
raise ValueError("Distance cannot be negative")
31-
3227
visited_all = (1 << n) - 1
3328

3429
@lru_cache(None)
@@ -45,11 +40,7 @@ def visit(city: int, mask: int) -> int:
4540
)
4641
min_cost = min(min_cost, new_cost)
4742
return min_cost
48-
4943
return visit(0, 1) # Start from city 0 with only city 0 visited
50-
51-
5244
if __name__ == "__main__":
5345
import doctest
54-
5546
doctest.testmod()

0 commit comments

Comments
 (0)