forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtravel_salesman.py
58 lines (47 loc) · 1.76 KB
/
travel_salesman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.
Example:
distances = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
Output: 80
"""
from functools import lru_cache
def tsp(distances: list[list[int]]) -> int:
"""
Solves TSP using dynamic programming.
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
80
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
69
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
Traceback (most recent call last):
...
ValueError: Distance cannot be negative
"""
n = len(distances)
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
raise ValueError("Distance cannot be negative")
visited_all = (1 << n) - 1
@lru_cache(None)
def visit(city: int, mask: int) -> int:
"""Recursively calculates the minimum cost of visiting all cities."""
if mask == visited_all:
return distances[city][0] # Return to start
min_cost = float('inf')
for next_city in range(n):
if not mask & (1 << next_city): # If next_city is unvisited
new_cost = distances[city][next_city] + visit(
next_city, mask | (1 << next_city)
)
min_cost = min(min_cost, new_cost)
return min_cost
return visit(0, 1) # Start from city 0 with only city 0 visited
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]) = }")
print(f"{tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]]) = }")