5
5
6
6
def tsp (distances : list [list [int ]]) -> int :
7
7
"""
8
- Solves the Travelling Salesman Problem (TSP) using
8
+ Solves the Travelling Salesman Problem (TSP) using
9
9
dynamic programming and bitmasking.
10
10
Args:
11
- distances: 2D list where distances[i][j] is the
11
+ distances: 2D list where distances[i][j] is the
12
12
distance between city i and city j.
13
13
Returns:
14
- Minimum cost to complete the
14
+ Minimum cost to complete the
15
15
tour visiting all cities.
16
16
Raises:
17
17
ValueError: If any distance is negative.
@@ -20,7 +20,7 @@ def tsp(distances: list[list[int]]) -> int:
20
20
80
21
21
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
22
22
69
23
- >>> 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]])
24
24
ValueError: Distance cannot be negative
25
25
"""
26
26
n = len (distances )
@@ -35,7 +35,7 @@ def visit(city: int, mask: int) -> int:
35
35
if mask == visited_all :
36
36
return distances [city ][0 ] # Return to start
37
37
38
- min_cost = float (' inf' ) # Large value to compare against
38
+ min_cost = float (" inf" ) # Large value to compare against
39
39
for next_city in range (n ):
40
40
if not mask & (1 << next_city ): # If unvisited
41
41
new_cost = distances [city ][next_city ] + visit (
@@ -49,4 +49,5 @@ def visit(city: int, mask: int) -> int:
49
49
50
50
if __name__ == "__main__" :
51
51
import doctest
52
+
52
53
doctest .testmod ()
0 commit comments