-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.v
94 lines (72 loc) · 1.63 KB
/
18.v
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import os
import math
import strconv
fn print_grid(grid [][]bool) {
for i in 0 .. grid.len {
for j in 0 .. grid[i].len {
print(if grid[i][j] { '#' } else { '.' })
}
print('\n')
}
}
fn solve_maze(grid [][]bool, sx int, sy int, ex int, ey int) int {
dirs := [[1, 0], [0, -1], [-1, 0], [0, 1]]
mut queue := [][]int{}
mut visited := map[string]int{}
mut min := max_int
queue << [sx, sy, 0]
visited['${sx},${sy}'] = 0
for queue.len > 0 {
curr := queue[0]
cx := curr[0]
cy := curr[1]
cc := curr[2]
queue.delete(0)
if cx == ex && cy == ey {
min = math.min(min, cc)
continue
}
for i in 0 .. 4 {
nx, ny := cx + dirs[i][0], cy + dirs[i][1]
if nx >= 0 && ny >= 0 && ny < grid.len && nx < grid[0].len && !grid[nx][ny] {
key := '${nx},${ny}'
nc := cc + 1
if key !in visited || visited[key] > nc {
visited[key] = nc
queue << [nx, ny, nc]
}
}
}
}
return min
}
fn p1(input string) ! {
lines := os.read_lines(input)!
mut grid := [][]bool{len: 71, init: []bool{len: 71, init: false}}
for i, line in lines {
x, y := line.split_once(',') or { '', '' }
if i == 1024 {
break
}
grid[strconv.atoi(x)!][strconv.atoi(y)!] = true
}
print_grid(grid)
println(solve_maze(grid, 0, 0, 70, 70))
}
fn p2(input string) ! {
lines := os.read_lines(input)!
mut grid := [][]bool{len: 71, init: []bool{len: 71, init: false}}
for line in lines {
x, y := line.split_once(',') or { '', '' }
grid[strconv.atoi(x)!][strconv.atoi(y)!] = true
if solve_maze(grid, 0, 0, 70, 70) == max_int {
print_grid(grid)
println(line)
break
}
}
}
fn main() {
p1('input')!
p2('input')!
}