Skip to content

Instantly share code, notes, and snippets.

@vjeranc
Last active December 13, 2022 22:39
Show Gist options
  • Save vjeranc/8691183db59cd175ab685aa194f76bef to your computer and use it in GitHub Desktop.
Save vjeranc/8691183db59cd175ab685aa194f76bef to your computer and use it in GitHub Desktop.
Day 12 solution without queues in Nim for Advent of Code 2022 at https://adventofcode.com/2022/day/12
import std/strutils
import std/sequtils
type Loc = tuple
x, y: int
proc parseGrid(): tuple[s: Loc, e: Loc, g: seq[seq[int]]] =
var
g: seq[seq[int]]
s, e: Loc
for line in lines("day12.input"):
g.add line.mapIt(it.ord)
for j in 0..<line.len:
if g[^1][j] == 'S'.ord:
g[^1][j] = 'a'.ord
s = (x: g.high, y: j)
elif g[^1][j] == 'E'.ord:
g[^1][j] = 'z'.ord
e = (x: g.high, y: j)
return (s, e, g)
let (s, e, g) = parseGrid()
proc sp(s: Loc, ascent: static bool = true): seq[seq[int]] =
var d: seq[seq[int]] = newSeq[seq[int]](g.len)
for i in 0..<g.len: d[i] = newSeq[int](g[i].len)
for i in 0..<g.len:
for j in 0..<g[i].len: d[i][j] = int.high-1
d[s.x][s.y] = 0
var ch = true
while ch:
ch = false
for x in 0..g.high:
for y in 0..g[x].high:
if d[x][y] == -1: continue
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
let (nx, ny) = (x + dx, y + dy)
if nx < 0 or nx > g.high or ny < 0 or ny > g[nx].high: continue
if ascent and g[nx][ny] - g[x][y] > 1: continue
if not ascent and g[x][y] - g[nx][ny] > 1: continue
if d[nx][ny] > d[x][y] + 1:
d[nx][ny] = d[x][y] + 1
ch = true
return d
echo "Part 1: ", sp(s)[e.x][e.y]
let d = sp(e, ascent=false)
var minDist = int.high
for i in 0..g.high:
for j in 0..g[i].high:
if g[i][j] == 'a'.ord:
minDist = min(minDist, d[i][j])
echo "Part 2: ", minDist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment