Skip to content

Instantly share code, notes, and snippets.

@vjeranc
Last active December 13, 2022 20:30
Show Gist options
  • Save vjeranc/009e31dabead77c8bbe1963c7d1081d0 to your computer and use it in GitHub Desktop.
Save vjeranc/009e31dabead77c8bbe1963c7d1081d0 to your computer and use it in GitHub Desktop.
Day 12 solution without queues for Advent of Code 2022 at https://adventofcode.com/2022/day/12
g = []
for line in open('day12.input'):
g.append([ord(c) for c in line.strip()])
n = len(g)
# find S and E and transform to ord('a') and ord('z')
s, e = None, None
for i in range(n):
for j in range(len(g[i])):
if g[i][j] == ord('S'):
g[i][j] = ord('a')
s = (i, j)
elif g[i][j] == ord('E'):
g[i][j] = ord('z')
e = (i, j)
def sp(s, ascent=True): # shortest path to all
x, y = s
d = [[1e9 for _ in range(len(g[i]))] for i in range(n)]
d[x][y] = 0
ch = True
while ch:
ch = False
for i in range(n):
for j in range(len(g[i])):
if d[i][j] == 1e9: continue
for dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)):
ni, nj = i + dx, j + dy
if ni < 0 or ni >= n or nj < 0 or nj >= len(g[i]): continue
if ascent and g[ni][nj] - g[i][j] > 1: continue
if not ascent and g[i][j] - g[ni][nj] > 1: continue
if d[ni][nj] > d[i][j] + 1:
d[ni][nj] = d[i][j] + 1
ch = True
return d
print("Part 1:", sp(s)[e[0]][e[1]])
d = sp(e, ascent=False)
mn = 1e9
for i in range(n):
for j in range(n):
if g[i][j] == ord('a'):
mn = min(mn, d[i][j])
print("Part 2:", mn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment