-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.nim
63 lines (49 loc) Β· 1.38 KB
/
part2.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
import std/heapqueue
import std/sequtils
var board = newSeq[seq[int]]()
for line in lines "input.txt":
var row = newSeq[int]()
for ch in line:
row.add(int(ch) - int('0'))
board.add(row)
type
Data = tuple[
pos: tuple[x: int, y: int],
dir: int,
s: int,
]
var
sum = high(int)
gx = board[0].len - 1
gy = board.len - 1
dirMap = [(0, -1), (-1, 0), (0, 1), (1, 0)]
hq = initHeapQueue[Data]()
seen = newSeq[Data]()
bs = newSeqWith(board.len, newSeqWith(board[0].len, newSeq[int](2)))
hq.push((pos: (0, 0), dir: 0, s: 0))
hq.push((pos: (0, 0), dir: 1, s: 0))
while hq.len != 0:
var
(pos, dir, s) = hq.pop()
(x, y) = pos
if bs[y][x][dir mod 2] != 0 and bs[y][x][dir mod 2] <= s:
continue
bs[y][x][dir mod 2] = s;
if x == gx and y == gy:
sum = min(sum, s)
continue
for id in [1, 3]:
var
(nx, ny, ns) = (x, y, s)
nd = (dir + id) mod 4
for i in 1 .. 10:
var (dx, dy) = dirMap[nd]
nx += dx
ny += dy
if not (nx >= 0 and nx < board[0].len and ny >= 0 and ny < board.len):
break
ns += board[ny][nx]
if i > 3:
hq.push((pos: (nx, ny), dir: nd, s: ns))
echo sum