From f4edfaa6802cdec39bc48f3b3e2c01b7564196be Mon Sep 17 00:00:00 2001 From: felixm Date: Fri, 20 Dec 2024 01:54:25 -0500 Subject: [PATCH] Solve 2024 day 20 --- 2024/d20.py | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 2024/d20.py diff --git a/2024/d20.py b/2024/d20.py new file mode 100644 index 0000000..f5f746a --- /dev/null +++ b/2024/d20.py @@ -0,0 +1,90 @@ +from collections import deque +from lib import get_data +from lib import Grid2D + + +data = """############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +""" +data = get_data(__file__) + +g = Grid2D(data) + +(start,) = g.find("S") +(end,) = g.find("E") + +cost = 0 +sd = dict() +de = dict() + +queue = deque([(start[0], start[1], 0)]) +seen = set() +while queue: + r, c, cost = queue.popleft() + + if (r, c) in sd: + continue + sd[(r, c)] = cost + + if (r, c) == end: + break + + for r, c in g.neighbors_ort((r, c)): + if g[(r, c)] != "#": + queue.append((r, c, cost + 1)) + +seen = set() +queue = deque([(end[0], end[1], 0)]) +while queue: + r, c, cost = queue.popleft() + + if (r, c) in de: + continue + de[(r, c)] = cost + + if (r, c) == start: + break + + for r, c in g.neighbors_ort((r, c)): + if g[(r, c)] != "#": + queue.append((r, c, cost + 1)) + +for max_steps in [2, 20]: + cheats = set() + for cr, cc in g.find("S."): + start = cr, cc, 0 + seen = set() + queue = deque([start]) + while queue: + r, c, steps = queue.popleft() + if steps > max_steps: + continue + + if (r, c) in seen: + continue + seen.add((r, c)) + + if g[(r, c)] != "#": + ncost = sd[(cr, cc)] + steps + de[(r, c)] + if cost - ncost >= 100: + cheats.add((cr, cc, r, c)) + + for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]: + nr, nc = r + dr, c + dc + if g.contains((nr, nc)): + queue.append((nr, nc, steps + 1)) + + print(len(cheats)) diff --git a/README.md b/README.md index e9cacdc..0a9ca82 100644 --- a/README.md +++ b/README.md @@ -310,5 +310,5 @@ and focus. Of course, learning more algorithms and techniques helps. - Day 17: `17:34:16 23722 0 >24h 17778 0` - Day 18: `14:35:01 20398 0 14:37:18 19550 0` - Day 19: `00:14:37 2001 0 00:19:43 1584 0` -- Day 20: +- Day 20: `01:08:53 3637 0 01:53:01 2837 0`