Skip to content

Commit dba4f07

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

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

dynamic_programming/travelling_salesman_problem.py

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

3+
34
def tsp(distances: list[list[int]]) -> int:
45
"""
5-
Solves the Travelling Salesman Problem (TSP)
6+
Solves the Travelling Salesman Problem (TSP)
67
using dynamic programming and bitmasking.
78
Args:
8-
distances: 2D list where distances[i][j]
9+
distances: 2D list where distances[i][j]
910
is the distance between city i and city j.
1011
Returns:
1112
Minimum cost to complete the tour visiting all cities.
@@ -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') # Large value to compare against
44+
min_cost = float("inf") # Large value to compare against
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,7 +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 city 0 visited
55+
56+
5357
if __name__ == "__main__":
5458
import doctest
59+
5560
doctest.testmod()

0 commit comments

Comments
 (0)