Skip to content

Commit 9a1bc9f

Browse files
committed
feat: travelling-salesman-bitmasking challenge
1 parent aeac041 commit 9a1bc9f

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed
Binary file not shown.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Challenge: Implement a solution for the travelling salesman problem using dynamic programming with bitmasking.
2+
# This challenge requires optimizing the search in an exponential state space.
3+
# Use object-oriented programming and follow the DRY principle.
4+
5+
from tsp import TravellingSalesman
6+
7+
def main():
8+
graph = [
9+
[0, 10, 15, 20],
10+
[10, 0, 35, 25],
11+
[15, 35, 0, 30],
12+
[20, 25, 30, 0]
13+
]
14+
tsp_solver = TravellingSalesman(graph)
15+
min_cost = tsp_solver.tsp(0, 1 << 0)
16+
print(f"Minimum travelling salesman cost: {min_cost}")
17+
18+
if __name__ == "__main__":
19+
main()
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List
2+
3+
class TravellingSalesman:
4+
def __init__(self, graph: List[List[int]]):
5+
self.graph = graph
6+
self.n = len(graph)
7+
self.ALL_VISITED = (1 << self.n) - 1
8+
self.memo = [[-1] * (1 << self.n) for _ in range(self.n)]
9+
10+
def tsp(self, pos: int, visited: int) -> int:
11+
if visited == self.ALL_VISITED:
12+
return self.graph[pos][0] # return to start
13+
14+
if self.memo[pos][visited] != -1:
15+
return self.memo[pos][visited]
16+
17+
ans = float('inf')
18+
for city in range(self.n):
19+
if (visited >> city) & 1 == 0:
20+
new_visited = visited | (1 << city)
21+
cost = self.graph[pos][city] + self.tsp(city, new_visited)
22+
ans = min(ans, cost)
23+
24+
self.memo[pos][visited] = ans
25+
return ans

0 commit comments

Comments
 (0)