-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (77 loc) · 1.46 KB
/
main.go
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
package main
import (
"fmt"
"github.com/devkvlt/aoc"
)
type Pos struct{ x, y int }
var (
grid = aoc.Lines("input")
height = len(grid)
width = len(grid[0])
trailheads []Pos
)
func init() {
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
if grid[y][x] == '0' {
trailheads = append(trailheads, Pos{x, y})
}
}
}
}
func elevation(p Pos) byte {
return grid[p.y][p.x] - '0'
}
func neighbors(p Pos) []Pos {
var neighbors []Pos
for _, n := range []Pos{{p.x, p.y + 1}, {p.x, p.y - 1}, {p.x + 1, p.y}, {p.x - 1, p.y}} {
if n.x >= 0 && n.x < width && n.y >= 0 && n.y < height && elevation(n) == elevation(p)+1 {
neighbors = append(neighbors, n)
}
}
return neighbors
}
func part1() {
score := 0
for _, head := range trailheads {
queue := []Pos{head}
seen := map[Pos]bool{}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
for _, next := range neighbors(curr) {
if elevation(next) == 9 {
if !seen[next] {
seen[next] = true
score++
}
} else {
queue = append(queue, next)
}
}
}
}
fmt.Println(score)
}
func part2() {
rating := 0
for _, head := range trailheads {
queue := []Pos{head}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
for _, next := range neighbors(curr) {
if elevation(next) == 9 {
rating++
} else {
queue = append(queue, next)
}
}
}
}
fmt.Println(rating)
}
func main() {
part1() // 517
part2() // 1116
}