adventofcode2024/day18/sol.py

61 lines
1.4 KiB
Python

from collections import defaultdict
import astar
def parse(file):
return [
tuple([int(x) for x in line.strip().split(',')])
for line in file
]
def solve(file, N=71, T=1024):
falling = parse(file)
inf = float('inf')
map = [[0]*N for _ in range(N)]
map = defaultdict(lambda: inf)
for i,p in enumerate(falling):
map[p] = i
sol = _solve(map, N, T)
print(sol)
print(len(sol[-1])-1)
def _solve(map, N=71, T=1024):
start = (0,0) # x,y,t
def neighbors(n):
x,y = n
def push(x,y):
if 0 <= x < N and 0 <= y < N:
if T <= map[x,y]:
out.append((1,(x,y)))
out = []
push(x+1,y)
push(x,y+1)
push(x-1,y)
push(x,y-1)
return out
end = N-1, N-1
def heuristic(n):
return abs(end[0] - n[0]) + abs(end[1] - n[1])
return astar.search(start, end, neighbors, heuristic)
import math
def solve2(file, N=71, T=1024):
falling = parse(file)
inf = float('inf')
map = [[0]*N for _ in range(N)]
map = defaultdict(lambda: inf)
for i,p in enumerate(falling):
map[p] = i
sol = _solve(map, N, i+1)
if math.isinf(sol[0]):
print(p)
break
solve(open("sample1.in"), N=7, T=12)
solve2(open("sample1.in"), N=7, T=12)
solve(open("input"), N=71, T=1024)
solve2(open("input"), N=71, T=1024)