-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (77 loc) · 1.66 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
package main
import (
"fmt"
"io"
"os"
"github.com/devries/advent_of_code_2022/utils"
"github.com/spf13/pflag"
)
const inputfile = "../inputs/day12.txt"
func main() {
pflag.Parse()
f, err := os.Open(inputfile)
utils.Check(err, "error opening input")
defer f.Close()
r := solve(f)
fmt.Println(r)
}
func solve(r io.Reader) int {
// To find the 'a' with the shortest path we just find the shortest path from the end
// to the first a we encounter
lines := utils.ReadLines(r)
maze := parse(lines)
seen := make(map[utils.Point]bool)
start := SearchPoint{maze.End, 0}
search := []SearchPoint{start}
for len(search) > 0 {
sp := search[0]
search = search[1:]
pos := sp.Pos
steps := sp.Steps
if seen[pos] {
continue
}
seen[pos] = true
if maze.Altitudes[pos] == 'a' {
return steps
}
for _, d := range utils.Directions {
p := pos.Add(d)
if maze.Altitudes[p] == 0 {
continue
}
if maze.Altitudes[pos]-1 <= maze.Altitudes[p] {
search = append(search, SearchPoint{p, steps + 1})
}
}
}
return 0
}
type Maze struct {
Altitudes map[utils.Point]rune
Start utils.Point
End utils.Point
}
type SearchPoint struct {
Pos utils.Point
Steps int
}
func parse(lines []string) Maze {
ret := Maze{make(map[utils.Point]rune), utils.Point{}, utils.Point{}}
for y := 0; y < len(lines); y++ {
ln := lines[len(lines)-y-1]
for x, c := range []rune(ln) {
switch c {
case 'S':
ret.Start = utils.Point{X: x, Y: y}
ret.Altitudes[ret.Start] = 'a'
case 'E':
ret.End = utils.Point{X: x, Y: y}
ret.Altitudes[ret.End] = 'z'
default:
ret.Altitudes[utils.Point{X: x, Y: y}] = c
}
}
}
return ret
}