-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.ha
59 lines (51 loc) · 1.32 KB
/
part2.ha
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
use fmt;
use io;
use os;
use strings;
fn read_map() [][]int = {
const file = os::open("input.txt")!;
defer io::close(file)!;
const lines = strings::split(strings::fromutf8(io::drain(file)!)!, "\n");
let rows: [][]int = [];
for (const line .. lines) {
if (len(line) == 0)
continue;
let row: []int = [];
for (const ch .. strings::toutf8(line))
append(row, (ch - '0'): int);
append(rows, row);
};
return rows;
};
fn step(map: [][]int, sx: int, sy: int, from: []int) int = {
const dirs = [[-1, 0], [0, -1], [1, 0], [0, 1]]; // Left, up, right, down
const next = map[sy][sx] + 1;
let sum = 0;
for (const dir .. dirs) {
if (dir[0] == from[0] && dir[1] == from[1])
continue;
// Find next position
let x = sx + dir[0];
let y = sy + dir[1];
if (x < 0 || x >= len(map[0]): int || y < 0 || y >= len(map): int)
continue;
if (map[y][x] != next) // Check if the height matches the next expected height
continue;
if (map[y][x] == 9) // Check if it is the end
sum += 1
else
sum += step(map, x, y, [-dir[0], -dir[1]]);
};
return sum;
};
export fn main() void = {
const map = read_map();
let sum = 0;
for (let y = 0z; y < len(map); y += 1) {
for (let x = 0z; x < len(map[0]); x += 1) {
if (map[y][x] == 0)
sum += step(map, x: int, y: int, [0, 0]);
};
};
fmt::printfln("{}", sum)!;
};