Solve 2024 day 12
This commit is contained in:
parent
022b95eb97
commit
efb1e3e551
61
2024/d12.py
Normal file
61
2024/d12.py
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
from lib import get_data
|
||||||
|
from lib import Grid2D
|
||||||
|
from collections import defaultdict
|
||||||
|
from collections import deque
|
||||||
|
|
||||||
|
data = get_data(__file__)
|
||||||
|
|
||||||
|
DIRS = {
|
||||||
|
"N": (-1, 0),
|
||||||
|
"E": (0, 1),
|
||||||
|
"S": (1, 0),
|
||||||
|
"W": (0, -1),
|
||||||
|
}.values()
|
||||||
|
|
||||||
|
|
||||||
|
g = Grid2D(data)
|
||||||
|
cs = defaultdict(set)
|
||||||
|
for row in range(g.n_rows):
|
||||||
|
for col in range(g.n_cols):
|
||||||
|
c = g[(row, col)]
|
||||||
|
cs[c].add((row, col))
|
||||||
|
|
||||||
|
t1, t2 = 0, 0
|
||||||
|
for c, cs in cs.items():
|
||||||
|
while cs:
|
||||||
|
peri = 0
|
||||||
|
start = cs.pop()
|
||||||
|
seen = set()
|
||||||
|
queue = deque([start])
|
||||||
|
fences = set()
|
||||||
|
while queue:
|
||||||
|
pos = queue.popleft()
|
||||||
|
if pos in seen:
|
||||||
|
continue
|
||||||
|
seen.add(pos)
|
||||||
|
|
||||||
|
for d in DIRS:
|
||||||
|
nb = d[0] + pos[0], d[1] + pos[1]
|
||||||
|
if g.contains(nb) and g[nb] == c:
|
||||||
|
queue.append(nb)
|
||||||
|
cs.discard(nb)
|
||||||
|
else:
|
||||||
|
peri += 1
|
||||||
|
nb = tuple(list(nb) + [d])
|
||||||
|
fences.add(nb)
|
||||||
|
|
||||||
|
nfences = set()
|
||||||
|
for row, col, dir in fences:
|
||||||
|
for dr, dc in [(1, 0), (0, 1)]:
|
||||||
|
nr, nc = row + dr, col + dc
|
||||||
|
if (nr, nc, dir) in fences:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
nfences.add((row, col, dir))
|
||||||
|
|
||||||
|
c_area = len(seen)
|
||||||
|
t1 += c_area * peri
|
||||||
|
t2 += c_area * len(nfences)
|
||||||
|
|
||||||
|
print(t1)
|
||||||
|
print(t2)
|
@ -301,6 +301,7 @@ and focus. Of course, learning more algorithms and techniques helps.
|
|||||||
- Day 8: `00:15:59 1742 0 00:26:56 2190 0`
|
- Day 8: `00:15:59 1742 0 00:26:56 2190 0`
|
||||||
- Day 9: `00:48:23 6055 0 01:09:38 3159 0`
|
- Day 9: `00:48:23 6055 0 01:09:38 3159 0`
|
||||||
- Day 10: `00:19:47 2976 0 00:20:47 2244 0`
|
- Day 10: `00:19:47 2976 0 00:20:47 2244 0`
|
||||||
- Day 11: `11 00:05:13 642 0 00:33:07 2673 0`
|
- Day 11: `00:05:13 642 0 00:33:07 2673 0`
|
||||||
|
- Day 12: `00:30:30 3540 0 11:41:33 16212 0`
|
||||||
|
- Day 13:
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user