Skip to content

Commit 5d02d22

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 9d8a653 commit 5d02d22

File tree

1 file changed

+27
-23
lines changed

1 file changed

+27
-23
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
11
#!/usr/bin/env python3
22

3+
34
def tsp(distances: list[list[int]]) -> int:
45
"""
5-
Solves the Travelling Salesman Problem (TSP)
6-
using dynamic programming and bitmasking.
7-
8-
Args:
9-
distances: 2D list where distances[i][j]
10-
is the distance between city i and city j.
11-
12-
Returns:
13-
Minimum cost to complete the tour visiting all cities.
14-
15-
Raises:
16-
ValueError: If any distance is negative.
17-
18-
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
19-
80
20-
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
21-
69
22-
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
23-
# doctest: +ELLIPSIS
24-
Traceback (most recent call last):
25-
...
26-
ValueError: Distance cannot be negative
6+
Solves the Travelling Salesman Problem (TSP)
7+
using dynamic programming and bitmasking.
8+
9+
Args:
10+
distances: 2D list where distances[i][j]
11+
is the distance between city i and city j.
12+
13+
Returns:
14+
Minimum cost to complete the tour visiting all cities.
15+
16+
Raises:
17+
ValueError: If any distance is negative.
18+
19+
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
20+
80
21+
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
22+
69
23+
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
24+
# doctest: +ELLIPSIS
25+
Traceback (most recent call last):
26+
...
27+
ValueError: Distance cannot be negative
2728
"""
2829
n = len(distances)
2930
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
@@ -40,7 +41,7 @@ def visit(city: int, mask: int) -> int:
4041
if memo[city][mask] != -1: # Return cached result if exists
4142
return memo[city][mask]
4243

43-
min_cost = float('inf') # Use infinity for initial comparison
44+
min_cost = float("inf") # Use infinity for initial comparison
4445
for next_city in range(n):
4546
if not (mask & (1 << next_city)): # If unvisited
4647
new_cost = distances[city][next_city] + visit(
@@ -49,8 +50,11 @@ def visit(city: int, mask: int) -> int:
4950
min_cost = min(min_cost, new_cost)
5051
memo[city][mask] = min_cost # Store result in the memoization table
5152
return min_cost
53+
5254
return visit(0, 1) # Start from city 0 with only city 0 visited
5355

56+
5457
if __name__ == "__main__":
5558
import doctest
59+
5660
doctest.testmod()

0 commit comments

Comments
 (0)