adventofcode2022/day12/sol.py

55 lines
1.2 KiB
Python
Raw Normal View History

2022-12-12 05:57:13 +00:00
import heapq
import string
2022-12-12 19:06:05 +00:00
2022-12-12 19:22:01 +00:00
elevation = {c:i for i, c in enumerate(string.ascii_lowercase)}
elevation['E'] = elevation['z']
elevation['S'] = elevation['a']
2022-12-12 05:57:13 +00:00
2022-12-12 19:06:05 +00:00
data = open("input").read().splitlines(False)
2022-12-12 19:22:01 +00:00
#print(*data, sep="\n")
2022-12-12 05:57:13 +00:00
2022-12-12 19:06:05 +00:00
extra = []
2022-12-12 19:22:01 +00:00
for y, row in enumerate(data):
for x, c in enumerate(row):
if c == 'S':
2022-12-12 05:57:13 +00:00
start = (x,y)
2022-12-12 19:22:01 +00:00
elif c == 'E':
2022-12-12 05:57:13 +00:00
goal = (x,y)
2022-12-12 19:22:01 +00:00
elif c == 'a':
2022-12-12 19:06:05 +00:00
# for part 2
extra.append((x,y))
2022-12-12 19:22:01 +00:00
def get(x, y):
return elevation[data[y][x]]
2022-12-12 19:06:05 +00:00
def solve(part):
q = [(0, start)]
if part == 2:
q.extend((0,p) for p in extra)
done = {}
while q:
cost, (x,y) = heapq.heappop(q)
if (x,y) in done:
continue
#print(x,y,cost)
if (x,y) == goal:
print('found', cost)
break
here = get(x,y)
done[(x,y)] = cost
2022-12-12 19:22:01 +00:00
def push(x,y):
2022-12-12 19:06:05 +00:00
if 0 <= y < len(data):
if 0 <= x < len(data[y]):
if get(x,y) <= here+1 and (x,y) not in done:
2022-12-12 19:22:01 +00:00
heapq.heappush(q, (cost+1, (x,y)))
push(x-1, y)
push(x+1,y)
push(x, y-1)
push(x, y+1)
2022-12-12 05:57:13 +00:00
2022-12-12 19:06:05 +00:00
solve(1)
solve(2)