File tree Expand file tree Collapse file tree 1 file changed +4
-4
lines changed
Expand file tree Collapse file tree 1 file changed +4
-4
lines changed Original file line number Diff line number Diff line change 11"""
22Dynamic Programming: Travelling Salesman Problem (TSP)
33-----------------------------------------------------
4- Solves the classic TSP using the Held– Karp dynamic programming approach.
4+ Solves the classic TSP using the Held Karp dynamic programming approach.
55
66Time Complexity: O(n^2 * 2^n)
77Space Complexity: O(n * 2^n)
1717 80
1818"""
1919
20- from functools import lru_cache
20+ import functools
2121
2222
2323def travelling_salesman (cost_matrix : list [list [int ]]) -> int :
2424 """
2525 Returns the minimum travel cost for visiting all cities and returning
26- to the starting city (0-indexed), using the Held– Karp DP approach.
26+ to the starting city (0-indexed), using the Held Karp DP approach.
2727
2828 Args:
2929 cost_matrix (list[list[int]]): A square matrix where cost_matrix[i][j]
@@ -35,7 +35,7 @@ def travelling_salesman(cost_matrix: list[list[int]]) -> int:
3535 n = len (cost_matrix )
3636 all_visited = (1 << n ) - 1 # bitmask with all cities visited
3737
38- @lru_cache ( maxsize = None )
38+ @functools . cache
3939 def dp (mask : int , pos : int ) -> int :
4040 # Base case: all cities visited, return cost to go back to start
4141 if mask == all_visited :
You can’t perform that action at this time.
0 commit comments