diff --git a/d10/run.py b/d10/run.py new file mode 100644 index 0000000..a6ad24b --- /dev/null +++ b/d10/run.py @@ -0,0 +1,23 @@ +import sys +from grid import * + +L = sys.stdin.read().strip().split("\n") +G = [list(map(int,l)) for l in L] + +def walk(grid, x, y, p=-1): + v = get_in_grid(G, x, y) + if v is None or v != p + 1: # wrong way + return + if v == 9: # end of trail + yield (x, y) + for dx, dy in MOVE4: + yield from walk(grid, x+dx, y+dy, p+1) + +U = R = 0 +for (x0,y0) in ((x,y) for y,row in enumerate(G) for x,v in enumerate(row) if v == 0): + s = set() + for ends in walk(G, x0, y0): + s.add(ends) + R += 1 + U += len(s) +print(U, R) diff --git a/lib/grid.py b/lib/grid.py new file mode 100644 index 0000000..b71c3b5 --- /dev/null +++ b/lib/grid.py @@ -0,0 +1,35 @@ +from typing import Any +from typing import Optional + +""" +same convention as SVG + W +(0,0)┌───────────► x + │ + H │ + │ + │ + ▼ + y +grid G store list of rows +to get G(x,y), must first extract row y and then col y => G[y][x] +""" + +def grid_geom(G:list[list[Any]]) -> tuple[int,int]: + H = len(G) + W = len(G[0]) + return W, H + +def in_grid(G:list[list[Any]], x:int, y:int) -> bool: + W, H = grid_geom(G) + return x>=0 and x=0 and y Optional[Any]: + if in_grid(G, x,y): + return G[y][x] + +UP = (0,-1) ; RIGHT = (1,0) ; DOWN = (0,1) ; LEFT = (-1,0) + +MOVE4 = [ UP, RIGHT, DOWN, LEFT ] +DIAG4 = [(1,1),(-1,-1),(1,-1),(-1,1)] +MOVE8 = MOVE4 + DIAG4