1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
#!/usr/bin/python3
import itertools
from typing import Generator, Iterator, Self, TextIO
class Grid:
@classmethod
def from_file(cls, f: TextIO) -> Self:
g = Grid()
g._grid = mkmap(
[[c for c in l if c != '\n'] for l in f.readlines()])
return g
def in_bounds_p(self, z: complex) -> bool:
return (
0 <= z.real < len(self._grid[0])
and 0 <= z.imag < len(self._grid)
)
def accessablep(self, z: complex) -> bool:
return self[z] is not None and self[z] < 4
def indicies(self) -> Iterator[complex]:
return itertools.starmap(complex, itertools.product(
range(len(self._grid[0])),
range(len(self._grid)),
))
def neighbors(self, z: complex) -> Generator[complex, None, None]:
for Δ in (
-1-1j, -1, -1+1j,
0-1j, 0+1j,
+1-1j, +1, +1+1j,
):
if self.in_bounds_p(z + Δ):
yield z + Δ
def __getitem__(self, z: complex) -> int | None:
return self._grid[int(z.real)][int(z.imag)]
def __setitem__(self, z: complex, n: int | None) -> None:
self._grid[int(z.real)][int(z.imag)] = n
def mkmap(xs: list[list[str]]) -> list[list[int]]:
def get(pos: complex) -> str:
r, i = map(int, (pos.real, pos.imag))
if 0 <= r < len(xs[0]) and 0 <= i < len(xs):
return xs[r][i]
return '.'
return [
[
sum(get(complex(i, j) + Δ) == '@' for Δ in [
-1-1j, -1, -1+1j,
0-1j, 0+1j,
+1-1j, +1, +1+1j,
])
if get(complex(i, j)) == '@'
else None
for j in range(len(xs[i]))
]
for i in range(len(xs))
]
def main() -> None:
with open('input', 'r') as f:
grid = Grid.from_file(f)
if PUZZLE_PART == 1:
acc = sum(grid.accessablep(z) for z in grid.indicies())
else:
acc = 0
while True:
breakp = True
for z in grid.indicies():
if not grid.accessablep(z):
continue
breakp = False
acc += 1
grid[z] = None
for p in grid.neighbors(z):
if grid[p] is not None:
grid[p] -= 1
if breakp:
break
print(acc)
if __name__ == '__main__':
main()
|