Skip to content

Commit 9d8a653

Browse files
authored
Update travelling_salesman_problem.py
1 parent 1769cb9 commit 9d8a653

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,56 @@
11
#!/usr/bin/env python3
22

3-
43
def tsp(distances: list[list[int]]) -> int:
54
"""
65
Solves the Travelling Salesman Problem (TSP)
76
using dynamic programming and bitmasking.
7+
88
Args:
99
distances: 2D list where distances[i][j]
1010
is the distance between city i and city j.
1111
1212
Returns:
13-
Minimum cost to complete the tour
14-
visiting all cities.
13+
Minimum cost to complete the tour visiting all cities.
14+
1515
Raises:
1616
ValueError: If any distance is negative.
17-
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
17+
18+
>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
1819
80
19-
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
20+
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
2021
69
21-
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
22-
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+
...
2326
ValueError: Distance cannot be negative
2427
"""
2528
n = len(distances)
2629
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
2730
raise ValueError("Distance cannot be negative")
2831

29-
# Create a memoization table
32+
# Memoization table
3033
memo = [[-1] * (1 << n) for _ in range(n)]
31-
visited_all = (1 << n) - 1
34+
visited_all = (1 << n) - 1 # All cities visited mask
3235

3336
def visit(city: int, mask: int) -> int:
3437
"""Recursively calculates the minimum cost to visit all cities."""
3538
if mask == visited_all:
36-
return distances[city][0] # Return to start
39+
return distances[city][0] # Return to the starting city
3740
if memo[city][mask] != -1: # Return cached result if exists
3841
return memo[city][mask]
39-
min_cost = 10**9 # Use a large integer instead of float('inf')
42+
43+
min_cost = float('inf') # Use infinity for initial comparison
4044
for next_city in range(n):
41-
if not mask & (1 << next_city): # If unvisited
45+
if not (mask & (1 << next_city)): # If unvisited
4246
new_cost = distances[city][next_city] + visit(
4347
next_city, mask | (1 << next_city)
4448
)
4549
min_cost = min(min_cost, new_cost)
4650
memo[city][mask] = min_cost # Store result in the memoization table
4751
return min_cost
48-
49-
return visit(0, 1) # Start from city 0 with city 0 visited
50-
52+
return visit(0, 1) # Start from city 0 with only city 0 visited
5153

5254
if __name__ == "__main__":
5355
import doctest
54-
5556
doctest.testmod()

0 commit comments

Comments
 (0)