Skip to content

Commit 612b116

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent be956ab commit 612b116

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

dynamic_programming/travelling_salesman_problem.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python3
22

3+
34
def tsp(distances: list[list[int]]) -> int:
45
"""
56
Solves the Travelling Salesman Problem (TSP)
@@ -8,7 +9,7 @@ def tsp(distances: list[list[int]]) -> int:
89
distances: 2D list where distances[i][j]
910
is the distance between city i and city j.
1011
Returns:
11-
Minimum cost to complete the
12+
Minimum cost to complete the
1213
tour visiting all cities.
1314
Raises:
1415
ValueError: If any distance is negative.
@@ -31,14 +32,15 @@ def tsp(distances: list[list[int]]) -> int:
3132
# Memoization table
3233
memo = [[-1] * (1 << n) for _ in range(n)]
3334
visited_all = (1 << n) - 1 # All cities visited mask
35+
3436
def visit(city: int, mask: int) -> int:
3537
"""Recursively calculates the minimum cost to visit all cities."""
3638
if mask == visited_all:
3739
return distances[city][0] # Return to the starting city
3840

3941
if memo[city][mask] != -1: # Return cached result if exists
4042
return memo[city][mask]
41-
min_cost = float('inf') # Use infinity for initial comparison
43+
min_cost = float("inf") # Use infinity for initial comparison
4244
for next_city in range(n):
4345
if not (mask & (1 << next_city)): # If unvisited
4446
new_cost = distances[city][next_city] + visit(
@@ -47,9 +49,13 @@ def visit(city: int, mask: int) -> int:
4749
min_cost = min(min_cost, new_cost)
4850
memo[city][mask] = int(min_cost) # Store result as an integer
4951
return memo[city][mask] # Return the cached result
52+
5053
return visit(0, 1) # Start from city 0 with city 0 visited
54+
55+
5156
if __name__ == "__main__":
5257
import doctest
58+
5359
try:
5460
doctest.testmod()
5561
except Exception as e:

0 commit comments

Comments
 (0)