-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
129 lines (110 loc) · 2.32 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"io"
aoc "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
grid := make(map[aoc.Position]int)
for row, line := range lines {
for col := 0; col < len(line); col++ {
r := rune(line[col])
grid[aoc.Position{row, col}] = aoc.RuneToInt(r)
}
}
return findBest(grid, aoc.Position{
Row: len(lines) - 1,
Col: len(lines[0]) - 1,
})
}
type Entry struct {
pos aoc.Position
risk int
}
func findBest(grid map[aoc.Position]int, target aoc.Position) int {
q := []Entry{{}}
visited := make(map[aoc.Position]int)
best := aoc.NewMiner()
for len(q) != 0 {
e := q[0]
q = q[1:]
if e.pos == target {
best.Add(e.risk + grid[target] - grid[aoc.Position{}])
continue
}
if risk, exists := visited[e.pos]; exists {
if risk <= e.risk {
continue
}
}
visited[e.pos] = e.risk
e.risk += grid[e.pos]
p := e.pos.Delta(-1, 0)
if _, exists := grid[p]; exists {
q = append(q, Entry{
pos: p,
risk: e.risk,
})
}
p = e.pos.Delta(1, 0)
if _, exists := grid[p]; exists {
q = append(q, Entry{
pos: p,
risk: e.risk,
})
}
p = e.pos.Delta(0, -1)
if _, exists := grid[p]; exists {
q = append(q, Entry{
pos: p,
risk: e.risk,
})
}
p = e.pos.Delta(0, 1)
if _, exists := grid[p]; exists {
q = append(q, Entry{
pos: p,
risk: e.risk,
})
}
}
return best.Get()
}
func fs2(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
grid := make(map[aoc.Position]int)
for row, line := range lines {
for col := 0; col < len(line); col++ {
r := rune(line[col])
grid[aoc.Position{row, col}] = aoc.RuneToInt(r)
}
}
maxRow := aoc.NewMaxer()
maxCol := aoc.NewMaxer()
for deltaRow := 0; deltaRow < 5; deltaRow++ {
for deltaCol := 0; deltaCol < 5; deltaCol++ {
if deltaRow == 0 && deltaCol == 0 {
continue
}
delta := deltaRow + deltaCol
for row, line := range lines {
for col := 0; col < len(line); col++ {
r := deltaRow*len(lines) + row
c := deltaCol*len(lines[0]) + col
v := grid[aoc.Position{row, col}] + delta
if v > 9 {
v = (v % 10) + 1
}
grid[aoc.Position{r, c}] =
v
maxRow.Add(r)
maxCol.Add(c)
}
}
}
}
return findBest(grid, aoc.Position{
Row: maxRow.Get(),
Col: maxCol.Get(),
})
}