From efb1e3e55176554dda2f6947f2173dac738a3aa9 Mon Sep 17 00:00:00 2001 From: felixm Date: Thu, 12 Dec 2024 23:57:04 -0500 Subject: [PATCH] Solve 2024 day 12 --- 2024/d12.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 5 +++-- 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 2024/d12.py diff --git a/2024/d12.py b/2024/d12.py new file mode 100644 index 0000000..0f57ff7 --- /dev/null +++ b/2024/d12.py @@ -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) diff --git a/README.md b/README.md index b148962..536e504 100644 --- a/README.md +++ b/README.md @@ -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 9: `00:48:23 6055 0 01:09:38 3159 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: