File tree Expand file tree Collapse file tree 3 files changed +44
-0
lines changed
3-HARD/Python/1-travelling-salesman-bitmasking/proposed-solution Expand file tree Collapse file tree 3 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 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 ()
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments