adventofcode2022/day12/sol.py

60 lines
1.3 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 05:57:13 +00:00
chars = 'ES'+string.ascii_lowercase
2022-12-12 19:06:05 +00:00
data = open("input").read().splitlines(False)
2022-12-12 05:57:13 +00:00
data = [list(map(chars.index, line)) for line in data]
#print(data)
2022-12-12 19:06:05 +00:00
2022-12-12 05:57:13 +00:00
def get(x, y):
return data[y][x]
2022-12-12 19:06:05 +00:00
extra = []
2022-12-12 05:57:13 +00:00
for x in range(len(data[0])):
for y in range(len(data)):
2022-12-12 19:06:05 +00:00
if get(x,y) == 1: # 'S'
2022-12-12 05:57:13 +00:00
data[y][x] = chars.index('a')
start = (x,y)
2022-12-12 19:06:05 +00:00
elif get(x,y) == 0: # 'E'
2022-12-12 05:57:13 +00:00
data[y][x] = chars.index('z')
goal = (x,y)
2022-12-12 19:06:05 +00:00
elif get(x,y) == 2: # 'a'
# for part 2
extra.append((x,y))
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
n = []
def check(x,y):
if 0 <= y < len(data):
if 0 <= x < len(data[y]):
if get(x,y) <= here+1 and (x,y) not in done:
n.append((cost+1, (x,y)))
check(x-1, y)
check(x+1,y)
check(x, y-1)
check(x, y+1)
for p in n:
heapq.heappush(q, p)
2022-12-12 05:57:13 +00:00
2022-12-12 19:06:05 +00:00
solve(1)
solve(2)