Skip to content

Create travel_salesman.py #11940

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions dynamic_programming/travel_salesman.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
Solves the Travelling Salesman Problem (TSP) using dynamic programming and bitmasking.

Example:
distances = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
Output: 80
"""

from functools import lru_cache


def tsp(distances: list[list[int]]) -> int:
"""
Solves TSP using dynamic programming.

>>> tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
80
>>> tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]])
69
>>> tsp([[0, 10, -15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
Traceback (most recent call last):
...
ValueError: Distance cannot be negative
"""
n = len(distances)
if any(distances[i][j] < 0 for i in range(n) for j in range(n)):
raise ValueError("Distance cannot be negative")

visited_all = (1 << n) - 1

@lru_cache(None)
def visit(city: int, mask: int) -> int:
"""Recursively calculates the minimum cost of visiting all cities."""
if mask == visited_all:
return distances[city][0] # Return to start

min_cost = float('inf')
for next_city in range(n):
if not mask & (1 << next_city): # If next_city is unvisited
new_cost = distances[city][next_city] + visit(
next_city, mask | (1 << next_city)
)
min_cost = min(min_cost, new_cost)
return min_cost

return visit(0, 1) # Start from city 0 with only city 0 visited


if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{tsp([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]) = }")

Check failure on line 57 in dynamic_programming/travel_salesman.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

dynamic_programming/travel_salesman.py:57:89: E501 Line too long (92 > 88)
print(f"{tsp([[0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 28], [21, 17, 28, 0]]) = }")

Check failure on line 58 in dynamic_programming/travel_salesman.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

dynamic_programming/travel_salesman.py:58:89: E501 Line too long (92 > 88)
Loading