Advertisement
hhoppe

Advent of code 2024 day 10

Dec 10th, 2024
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. def day10(s, part2=False):
  2.   grid = np.array([list(line) for line in s.splitlines()], int)
  3.   grid = np.pad(grid, 1, constant_values=-1)
  4.   trailheads = np.argwhere(grid == 0)
  5.   neighbors = ((0, -1), (0, 1), (-1, 0), (1, 0))
  6.   total = 0
  7.  
  8.   for y0, x0 in trailheads:
  9.     if not part2:
  10.       active = {(y0, x0)}  # Set of positions reached after `dist` moves.
  11.       for dist in range(1, 10):
  12.         active2 = set()
  13.         for y, x in active:
  14.           for dy, dx in neighbors:
  15.             y2, x2 = y + dy, x + dx
  16.             if grid[y2, x2] == dist:
  17.               active2.add((y2, x2))
  18.         active = active2
  19.       total += len(active)
  20.  
  21.     else:
  22.       active = collections.Counter([(y0, x0)])  # Number of paths reaching position.
  23.       for dist in range(1, 10):
  24.         active2 = collections.Counter()
  25.         for (y, x), count in active.items():
  26.           for dy, dx in neighbors:
  27.             y2, x2 = y + dy, x + dx
  28.             if grid[y2, x2] == dist:
  29.               active2[y2, x2] += count
  30.         active = active2
  31.       total += active.total()
  32.  
  33.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement