Advertisement
hhoppe

Advent of code 2024 day 16

Dec 16th, 2024 (edited)
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. def day16(s, *, part2=False):
  2.   grid = np.array([list(line) for line in s.splitlines()])
  3.   ((y0, x0),) = np.argwhere(grid == 'S')
  4.   ((yl, xl),) = np.argwhere(grid == 'E')
  5.   state = y0, x0, 0, 1  # y, x, dy, dx.
  6.   distance = collections.defaultdict(lambda: 10**9)  # For Dijkstra.
  7.   distance[state] = 0
  8.   pq = [(0, state)]
  9.  
  10.   def neighbors(d, state, sign=1):
  11.     y, x, dy, dx = state
  12.     yield d + sign, (y + dy * sign, x + dx * sign, dy, dx)
  13.     yield d + 1000 * sign, (y, x, -dx, dy)
  14.     yield d + 1000 * sign, (y, x, dx, -dy)
  15.  
  16.   while pq:
  17.     d, state = heapq.heappop(pq)
  18.  
  19.     if state[:2] == (yl, xl):
  20.  
  21.       def visit_paths(state):
  22.         d = distance.pop(state)  # Deletion for speedup.
  23.         grid[state[:2]] = 'O'
  24.         for d, state in neighbors(d, state, sign=-1):
  25.           if d == distance[state]:
  26.             visit_paths(state)
  27.  
  28.       visit_paths(state)
  29.       return (grid == 'O').sum() if part2 else d
  30.  
  31.     for d, state in neighbors(d, state):
  32.       if grid[state[:2]] != '#' and d < distance[state]:
  33.         distance[state] = d
  34.         heapq.heappush(pq, (d, state))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement