Advertisement
hhoppe

Advent of code 2023 day 16

Dec 15th, 2023 (edited)
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. @numba.njit  # Optional speedup.
  2. def day16_num_visited(grid, start):  # start == (y, x, dir); dir 0,1,2,3 == S,E,N,W.
  3.   visited = np.full((*grid.shape, 4), False)
  4.   stack = [start]
  5.   while stack:
  6.     y, x, dir = stack.pop()
  7.     while 0 <= y < grid.shape[0] and 0 <= x < grid.shape[1] and not visited[y, x, dir]:
  8.       visited[y, x, dir] = True
  9.       match grid[y, x]:
  10.         case 92:  # ord('\\').
  11.           dir = (1, 0, 3, 2)[dir]
  12.         case 47:  # ord('/').
  13.           dir = 3 - dir
  14.         case 45:  # ord('-').
  15.           if dir in (0, 2):
  16.             dir = 1
  17.             stack.append((y, x, 3))
  18.         case 124:  # ord('|').
  19.           if dir in (1, 3):
  20.             dir = 0
  21.             stack.append((y, x, 2))
  22.       y, x = y + (1, 0, -1, 0)[dir], x + (0, 1, 0, -1)[dir]
  23.  
  24.   return (visited.sum(2) > 0).sum()  # visited.any(2).sum() if not numba.
  25.  
  26.  
  27. def day16(s, *, part2=False):
  28.   grid = np.array([[ord(ch) for ch in line] for line in s.splitlines()], np.uint8)
  29.  
  30.   if not part2:
  31.     return day16_num_visited(grid, (0, 0, 1))
  32.  
  33.   starts = (
  34.       [(0, x, 0) for x in range(grid.shape[1])]
  35.       + [(grid.shape[0] - 1, x, 2) for x in range(grid.shape[1])]
  36.       + [(y, 0, 1) for y in range(grid.shape[0])]
  37.       + [(y, grid.shape[1] - 1, 3) for y in range(grid.shape[0])]
  38.   )
  39.   return max(day16_num_visited(grid, start) for start in starts)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement