Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit b2d0c34

Browse files
authoredOct 10, 2024··
Update travelling_salesman_problem.py
1 parent 92e121f commit b2d0c34

File tree

1 file changed

+19
-35
lines changed

1 file changed

+19
-35
lines changed
 
Lines changed: 19 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,26 @@
1-
"""
2-
Given a list of cities and the distances between every pair of cities, the Travelling Salesman Problem (TSP) is to
3-
find the shortest possible route that visits every city exactly once and returns to the starting city.
4-
5-
This problem can be solved using the concept of "DYNAMIC PROGRAMMING".
6-
7-
We use a bitmask to represent which cities have been visited and calculate the minimum cost to complete the tour.
8-
9-
Example - distances = [
10-
[0, 10, 15, 20],
11-
[10, 0, 35, 25],
12-
[15, 35, 0, 30],
13-
[20, 25, 30, 0]
14-
]
15-
Output: 80
16-
"""
1+
#!/usr/bin/env python3
172

183
from functools import lru_cache
194

205

216
def tsp(distances: list[list[int]]) -> int:
227
"""
23-
The tsp function solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.
24-
It calculates the minimum cost to visit all cities and return to the starting city.
8+
Solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.
9+
10+
Args:
11+
distances: A 2D list where distances[i][j] represents the distance between city i and city j.
12+
13+
Returns:
14+
The minimum cost to complete the tour visiting all cities.
15+
16+
Raises:
17+
ValueError: If any distance is negative.
2518
2619
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
2720
80
2821
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
2922
69
30-
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
23+
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]) # doctest: +ELLIPSIS
3124
Traceback (most recent call last):
3225
...
3326
ValueError: Distance cannot be negative
@@ -36,35 +29,26 @@ def tsp(distances: list[list[int]]) -> int:
3629
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
3730
raise ValueError("Distance cannot be negative")
3831

39-
VISITED_ALL = (1 << n) - 1
32+
visited_all = (1 << n) - 1
4033

4134
@lru_cache(None)
4235
def visit(city: int, mask: int) -> int:
43-
"""
44-
Recursively calculate the minimum cost of visiting all cities, starting at 'city' with visited cities encoded in 'mask'.
45-
"""
46-
if mask == VISITED_ALL:
47-
return distances[city][0] # Return to the starting city
36+
"""Recursively calculates the minimum cost of visiting all cities."""
37+
if mask == visited_all:
38+
return distances[city][0] # Return to start
4839

49-
min_cost = float("inf")
40+
min_cost = float('inf')
5041
for next_city in range(n):
51-
if not mask & (1 << next_city): # If the next_city is not visited
42+
if not mask & (1 << next_city): # If next_city is unvisited
5243
new_cost = distances[city][next_city] + visit(
5344
next_city, mask | (1 << next_city)
5445
)
5546
min_cost = min(min_cost, new_cost)
5647
return min_cost
5748

58-
return visit(0, 1) # Start at city 0 with only city 0 visited
49+
return visit(0, 1) # Start from city 0 with only city 0 visited
5950

6051

6152
if __name__ == "__main__":
6253
import doctest
63-
6454
doctest.testmod()
65-
print(
66-
f"{tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]) = }"
67-
)
68-
print(
69-
f"{tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]]) = }"
70-
)

0 commit comments

Comments
 (0)
Please sign in to comment.