Files
aoc/2022/12/l.py
2023-11-30 19:20:34 +02:00

71 lines
1.4 KiB
Python

import os
import numpy
from collections import deque
input = open(os.path.dirname(__file__) +
"/input.txt", "r").readlines()
start = ()
end = ()
terrain = []
for Y, y in enumerate(input):
y = y.strip()
cur = []
for X, x in enumerate(y):
h = ord(x)-ord('a')+1
if (x == 'S'):
h = 1
start = (Y, X)
if (x == 'E'):
h = 26
end = (Y, X)
cur.append(h)
terrain.append(cur)
H = len(terrain)
W = len(terrain[0])
neighbours = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def find_path(coords):
paths = []
for n in neighbours:
check = tuple(numpy.add(coords, n))
if 0 <= check[0] < H and 0 <= check[1] < W and coords != check:
if terrain[check[0]][check[1]] <= terrain[coords[0]][coords[1]]+1:
paths.append(check)
return paths
def solve(p):
Q = deque()
if (p == 2):
for y in range(H):
for x in range(W):
if terrain[y][x] == 1:
Q.append(((y, x), 0))
else:
Q.append((start, 0))
V = set()
while Q:
cur_pos, d = Q.popleft()
if cur_pos in V:
continue
V.add(cur_pos)
if cur_pos == end:
return d
tocheck = find_path(cur_pos)
for node in tocheck:
Q.append((node, d+1))
print(solve(1))
print(solve(2))