Files
advent-of-code/2022/12/part1
2022-12-13 00:13:15 +00:00

64 lines
1.4 KiB
Python
Executable File

#!/usr/bin/env python
import math
MAP = []
START = (0, 0)
END = (0, 0)
DISTANCES = {}
def possible(x, y):
global MAP
threshold = MAP[y][x] + 1 # Can't go higher than this, can always go lower
points = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
out = []
for (x,y) in points:
if x < 0 or y < 0:
continue
if len(MAP) < y+1 or len(MAP[y]) < x+1:
continue
if MAP[y][x] > threshold:
continue
out.append((x,y))
return out
with open('input') as f:
for y, line in enumerate(f):
row = []
for x, byte in enumerate(line.rstrip()):
DISTANCES[(x,y)] = math.inf
if byte == 'S':
byte = 'a'
START = (x,y)
DISTANCES[START] = 0
elif byte == 'E':
byte = 'z'
END = (x,y)
row.append(ord(byte) - ord('a'))
MAP.append(row)
visited = set([])
queue = [START]
while len(queue) > 0:
pos = queue.pop(0)
visited.add(pos)
for neighbour in possible(*pos):
if neighbour == END:
print(DISTANCES[pos] + 1)
quit()
if DISTANCES[neighbour] > DISTANCES[pos] + 1:
DISTANCES[neighbour] = DISTANCES[pos] + 1
if neighbour not in visited and neighbour not in queue:
queue.append(neighbour)
print("Couldn't find it!")