1
0
Fork 0
aoc2022/12/solution.py

53 lines
1.4 KiB
Python
Executable File

#!/usr/bin/env python3
import sys
from collections import deque
def solve(hmap, startpos, endpos, reverse = False):
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
h, w = len(hmap), len(hmap[0])
visited = set()
visited.add(startpos)
minsteps = float("inf")
queue = deque([(*startpos, 0)])
while len(queue):
y, x, steps = queue.popleft()
if (reverse and hmap[y][x] == ord("a")) or (y, x) == endpos:
minsteps = min(minsteps, steps)
continue
for d in dirs:
ny, nx = y + d[0], x + d[1]
if 0 <= ny < h and 0 <= nx < w:
diff = hmap[ny][nx] - hmap[y][x]
if reverse:
cond = diff == -1 or hmap[ny][nx] >= hmap[y][x]
else:
cond = diff == 1 or hmap[ny][nx] <= hmap[y][x]
if cond:
c = (ny, nx)
if c not in visited:
visited.add(c)
queue.append((*c, steps + 1))
return minsteps
hmap = [list(l.strip()) for l in sys.stdin]
for i, y in enumerate(hmap):
for j, x in enumerate(y):
if x == "S":
startpos = (i, j)
hmap[i][j] = "a"
elif x == "E":
endpos = (i, j)
hmap[i][j] = "z"
hmap[i][j] = ord(hmap[i][j])
print("Silver:", solve(hmap, startpos, endpos))
print("Gold:", solve(hmap, endpos, startpos, True))