imashutosh51

Traveling Salesman problem

May 20th, 2026 (edited)
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.53 KB | None | 0 0
  1. '''
  2. Start at city 0. From every city, try visiting all unvisited cities one by one — keep going deeper until all cities are visited.
  3. At that point, return the cost of going back to city 0.
  4.  
  5. As the recursion unwinds, each call receives the "best cost from here onwards" from its children, adds its own travel cost,
  6. and saves the best result for that (current_city, visited_set) state in memo — so if we ever land on the same city with the same visited set again,
  7. we skip recomputing and directly return the saved answer.
  8. '''
  9. '''
  10. Start at city 0. From every city, try visiting all unvisited cities one by one — keep going deeper until all cities are visited.
  11. At that point, return the cost of going back to city 0.
  12.  
  13. As the recursion unwinds, each call receives the "best cost from here onwards" from its children, adds its own travel cost,
  14. and saves the best result for that (current_city, visited_set) state in memo — so if we ever land on the same city with the same visited set again,
  15. we skip recomputing and directly return the saved answer.
  16.  
  17. State is (city,(visited cities)) visited cities can be any subset of N ie. 2^N and city can be N so total N*2^N
  18. each state we are doing sorting before pushing it into table or making a key, so visited can be max size=N so O(NlogN) for sorting for the key,then each state we are traversing O(N), then each state work= O(N+Nlog(N))=O(NLog(N)) as they are doing sequential.
  19. for getting the next city to visit so O(N) total N^2*2^Nlog(N)
  20.  
  21. This can be improved by using the mask for visited cities in the dictionary 101101 kind of, which will reduce the everytime sorting overhead of log(N)
  22. '''
  23. def dfs(city, visited, cost, n, memo):
  24.     if len(visited) == n:
  25.         return cost[city][0]
  26.  
  27.     key = (city, tuple(sorted(visited))) #sorted is needed otherwise same key can be multiple keys if shuffled
  28.     if key in memo:
  29.         return memo[key]
  30.  
  31.     ans = float('inf')
  32.     for nxt in range(n):
  33.         if nxt not in visited:
  34.             visited.add(nxt)
  35.             ans = min(ans, cost[city][nxt] + dfs(nxt, visited, cost, n, memo))
  36.             visited.remove(nxt)  # backtrack
  37.  
  38.     memo[key] = ans
  39.     return ans
  40.  
  41. #Visited cities also stored int the dictionary or dp because we will avoid the already visited cities
  42. class Solution:
  43.     def tsp(self, cost):
  44.         n = len(cost)
  45.         memo = {} # (cur_city, {visited}): cur_city to next unvisited city cost+ min of all dfs routes
  46.         visited = {0}
  47.         ans=dfs(0, visited, cost, n, memo)
  48.         return ans
  49.        
  50.        
Advertisement
Add Comment
Please, Sign In to add comment