aoc

Advent of Code Solutions
git clone git://git.alexkarle.com.com/aoc
Log | Files | Refs | README | LICENSE

commit 5e0ba25451e791762a9be69aceb8f9f5b3f2d690 (patch)
parent 651137afb4b61d305cf3383e273feffef9cc079f
Author: Alex Karle <alex@alexkarle.com>
Date:   Tue, 10 Dec 2024 14:12:38 +0100

2024: Add Day 10

Easy DFS :)

Diffstat:
A2024/10/1.py | 43+++++++++++++++++++++++++++++++++++++++++++
A2024/10/2.py | 41+++++++++++++++++++++++++++++++++++++++++
2 files changed, 84 insertions(+), 0 deletions(-)

diff --git a/2024/10/1.py b/2024/10/1.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import sys + +def parse(): + G = [] + for l in sys.stdin: + G.append([int(x) for x in l.strip()]) + return G + +def safeget(G, i, j): + if i < 0 or j < 0 or i >= len(G) or j >= len(G[0]): + return None + return G[i][j] + +def score(G, i0, j0): + s = 0 + seen = set() + stk = [(i0, j0)] + while stk: + (i, j) = stk.pop() + seen.add((i, j)) + height = G[i][j] + if height == 9: + s += 1 + continue + for pos in [(i+1,j),(i-1,j),(i,j-1),(i,j+1)]: + next = safeget(G, pos[0], pos[1]) + if next == height + 1 and pos not in seen: + stk.append(pos) + return s + + +def sol(G): + tot = 0 + for i in range(len(G)): + for j in range(len(G[0])): + if G[i][j] == 0: + tot += score(G, i, j) + return tot + +if __name__ == '__main__': + G = parse() + print(sol(G)) diff --git a/2024/10/2.py b/2024/10/2.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +import sys + +def parse(): + G = [] + for l in sys.stdin: + G.append([int(x) for x in l.strip()]) + return G + +def safeget(G, i, j): + if i < 0 or j < 0 or i >= len(G) or j >= len(G[0]): + return None + return G[i][j] + +def score(G, i0, j0): + s = 0 + stk = [(i0, j0)] + while stk: + (i, j) = stk.pop() + height = G[i][j] + if height == 9: + s += 1 + continue + for pos in [(i+1,j),(i-1,j),(i,j-1),(i,j+1)]: + next = safeget(G, pos[0], pos[1]) + if next == height + 1: + stk.append(pos) + return s + + +def sol(G): + tot = 0 + for i in range(len(G)): + for j in range(len(G[0])): + if G[i][j] == 0: + tot += score(G, i, j) + return tot + +if __name__ == '__main__': + G = parse() + print(sol(G))