1
1
#!/usr/bin/env python3
2
2
3
+
3
4
def tsp (distances : list [list [int ]]) -> int :
4
5
"""
5
6
Solves the Travelling Salesman Problem (TSP)
@@ -8,7 +9,7 @@ def tsp(distances: list[list[int]]) -> int:
8
9
distances: 2D list where distances[i][j]
9
10
is the distance between city i and city j.
10
11
Returns:
11
- Minimum cost to complete the
12
+ Minimum cost to complete the
12
13
tour visiting all cities.
13
14
Raises:
14
15
ValueError: If any distance is negative.
@@ -31,14 +32,15 @@ def tsp(distances: list[list[int]]) -> int:
31
32
# Memoization table
32
33
memo = [[- 1 ] * (1 << n ) for _ in range (n )]
33
34
visited_all = (1 << n ) - 1 # All cities visited mask
35
+
34
36
def visit (city : int , mask : int ) -> int :
35
37
"""Recursively calculates the minimum cost to visit all cities."""
36
38
if mask == visited_all :
37
39
return distances [city ][0 ] # Return to the starting city
38
40
39
41
if memo [city ][mask ] != - 1 : # Return cached result if exists
40
42
return memo [city ][mask ]
41
- min_cost = float (' inf' ) # Use infinity for initial comparison
43
+ min_cost = float (" inf" ) # Use infinity for initial comparison
42
44
for next_city in range (n ):
43
45
if not (mask & (1 << next_city )): # If unvisited
44
46
new_cost = distances [city ][next_city ] + visit (
@@ -47,9 +49,13 @@ def visit(city: int, mask: int) -> int:
47
49
min_cost = min (min_cost , new_cost )
48
50
memo [city ][mask ] = int (min_cost ) # Store result as an integer
49
51
return memo [city ][mask ] # Return the cached result
52
+
50
53
return visit (0 , 1 ) # Start from city 0 with city 0 visited
54
+
55
+
51
56
if __name__ == "__main__" :
52
57
import doctest
58
+
53
59
try :
54
60
doctest .testmod ()
55
61
except Exception as e :
0 commit comments