adventofcode2024/day18/sol.py

60 lines
1.3 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 = defaultdict(lambda: 1)
for i,p in enumerate(falling):
if i > T:
break
map[p] = 0
sol = _solve(map, N)
print(sol)
print(len(sol[-1])-1)
def _solve(map, N):
start = (0,0) # x,y
end = N-1, N-1
def neighbors(n):
x,y = n
def push(x,y):
if 0 <= x < N and 0 <= y < N:
if 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
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):
falling = parse(file)
map = defaultdict(lambda: 1)
for i,p in enumerate(falling):
map[p] = 0
sol = _solve(map, N)
if math.isinf(sol[0]):
print(p)
break
solve(open("sample1.in"), N=7, T=12)
solve2(open("sample1.in"), N=7)
print()
solve(open("input"), N=71, T=1024)
solve2(open("input"), N=71)