Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def day12(s, *, part2=False):
- grid = np.array([list(line) for line in s.splitlines()])
- grid = np.pad(grid, 1, constant_values='.')
- visited = grid == '.'
- total = 0
- for (y, x), ch in np.ndenumerate(grid):
- if visited[y, x]:
- continue
- visited[y, x] = True
- area = perimeter = sides = 0
- stack = [(y, x)]
- while stack:
- y, x = stack.pop()
- area += 1
- sames = []
- for dy, dx in ((-1, 0), (0, -1), (1, 0), (0, 1)):
- ny, nx = y + dy, x + dx
- same = grid[ny, nx] == ch
- sames.append((dy, dx, same))
- if same:
- if not visited[ny, nx]:
- visited[ny, nx] = True
- stack.append((ny, nx))
- else:
- perimeter += 1
- sames.append(sames[0])
- for (dy1, dx1, same1), (dy2, dx2, same2) in itertools.pairwise(sames):
- sides += (
- (not same1 and not same2)
- or (same1 and same2 and grid[y + dy1 + dy2, x + dx1 + dx2] != ch)
- )
- total += area * (sides if part2 else perimeter)
- return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement