Advertisement
petrlos

Untitled

Mar 22nd, 2023
561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. import heapq
  2.  
  3. def dijkstra(valves, source):
  4.     pq = [(0, float('inf'), source)]  # (total flow rate, distance, valve)
  5.     dist = {source: 0}  # distance from source
  6.     flow = {source: float('inf')}  # total flow rate from source
  7.     prev = {}  # previous valve in the path
  8.    
  9.     while pq:
  10.         flow_rate, distance, valve = heapq.heappop(pq)
  11.         if distance > 30:  # stop searching after 30 minutes
  12.             break
  13.         if flow_rate < flow[valve]:
  14.             continue  # this valve has already been visited with higher flow rate
  15.         for neighbor, flow_rate_neighbor in valves[valve]:
  16.             new_flow_rate = min(flow[valve], flow_rate_neighbor)
  17.             new_distance = distance + 1
  18.             if neighbor not in dist or new_flow_rate > flow[neighbor]:
  19.                 flow[neighbor] = new_flow_rate
  20.                 dist[neighbor] = new_distance
  21.                 prev[neighbor] = valve
  22.                 heapq.heappush(pq, (new_flow_rate, new_distance, neighbor))
  23.  
  24.     return prev, flow
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement