Skip to content

Instantly share code, notes, and snippets.

@object
Last active December 10, 2024 08:23
Show Gist options
  • Save object/b114152d033425948509aebbcd24b2d9 to your computer and use it in GitHub Desktop.
Save object/b114152d033425948509aebbcd24b2d9 to your computer and use it in GitHub Desktop.
Advent of Code 2024, day 10
import sys
from itertools import combinations
sys.setrecursionlimit(10**6)
with open("./data/input10.txt") as inputFile:
input = inputFile.read().splitlines()
trailheads = []
grid = []
for r in range(len(input)):
row = []
for c in range(len(input[r])):
n = int(input[r][c])
if n == 0: trailheads.append((r,c))
row.append(int(input[r][c]))
grid.append(row)
def get_neighbors(grid, pt):
neighbors = []
for r in range(max(0, pt[0]-1), min(len(grid), pt[0]+2)):
for c in range(max(0, pt[1]-1), min(len(grid[r]), pt[1]+2)):
if not (r == pt[0] and c == pt[1]) and (r == pt[0] or c == pt[1]):
neighbors.append((r,c))
return neighbors
def get_paths(grid, start, condition):
paths = []
for point in get_neighbors(grid, start):
if condition(grid[point[0]][point[1]], grid[start[0]][start[1]]):
for subpath in get_paths(grid, point, condition):
paths.append([start] + subpath)
if len(paths) == 0:
return [[start]]
else:
return paths
res1 = 0
res2 = 0
for th in trailheads:
s = set()
for t in get_paths(grid, th, lambda x, y: x == y+1):
if len(t) == 10:
s.add(t[9])
res2 += 1
res1 += len(s)
# Part 1:
print(res1)
# Part 2:
print(res2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment