day 18 part 2

main
magical 2024-12-18 05:28:30 +00:00
parent 16637ab722
commit cc853a4dcd
2 changed files with 45 additions and 32 deletions

View File

@ -28,8 +28,8 @@ def search(start, is_goal, neighbors, heuristic=None, worst=None):
done[this] = (cost_so_far, prev)
if is_goal(this):
print("astar: visited", len(done), "nodes")
print("astar: pending", len(q), "nodes")
#print("astar: visited", len(done), "nodes")
#print("astar: pending", len(q), "nodes")
# reconsruct the path
n = this
path = []

View File

@ -7,41 +7,54 @@ def parse(file):
for line in file
]
def solve(file, N=70, T=1024):
def solve(file, N=71, T=1024):
falling = parse(file)
start = (0,0,0) # x,y,t
map = [[0]*N for _ in range(N)]
inf = float('inf')
map = [[0]*N for _ in range(N)]
map = defaultdict(lambda: inf)
for t,p in enumerate(falling):
map[p] = t
def neighbors(n):
x,y,t = n
#if T < map[x,y]:
# can't move out of a blocked space
# return []
def push(x,y,t):
if 0 <= x < N and 0 <= y < N:
if T <= map[x,y]:
out.append((1,(x,y,t)))
out = []
push(x+1,y,t+1)
push(x,y+1,t+1)
push(x-1,y,t+1)
push(x,y-1,t+1)
return out
end = N-1, N-1
def isgoal(n):
x,y,_ = n
return (x,y) == end
sol = astar.search(start, isgoal, neighbors)
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)