Advertisement
hhoppe

Advent of code 2024 day 12

Dec 12th, 2024
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. def day12(s, *, part2=False):
  2.   grid = np.array([list(line) for line in s.splitlines()])
  3.   grid = np.pad(grid, 1, constant_values='.')
  4.   visited = grid == '.'
  5.   total = 0
  6.  
  7.   for (y, x), ch in np.ndenumerate(grid):
  8.     if visited[y, x]:
  9.       continue
  10.     visited[y, x] = True
  11.     area = perimeter = sides = 0
  12.     stack = [(y, x)]
  13.     while stack:
  14.       y, x = stack.pop()
  15.       area += 1
  16.       sames = []
  17.       for dy, dx in ((-1, 0), (0, -1), (1, 0), (0, 1)):
  18.         ny, nx = y + dy, x + dx
  19.         same = grid[ny, nx] == ch
  20.         sames.append((dy, dx, same))
  21.         if same:
  22.           if not visited[ny, nx]:
  23.             visited[ny, nx] = True
  24.             stack.append((ny, nx))
  25.         else:
  26.           perimeter += 1
  27.       sames.append(sames[0])
  28.       for (dy1, dx1, same1), (dy2, dx2, same2) in itertools.pairwise(sames):
  29.         sides += (
  30.             (not same1 and not same2)
  31.             or (same1 and same2 and grid[y + dy1 + dy2, x + dx1 + dx2] != ch)
  32.         )
  33.    
  34.     total += area * (sides if part2 else perimeter)
  35.  
  36.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement