-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (84 loc) · 1.96 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
package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/devries/advent_of_code_2021/utils"
"github.com/spf13/pflag"
)
func main() {
pflag.Parse()
f, err := os.Open("../inputs/day12.txt")
utils.Check(err, "error opening input.txt")
defer f.Close()
r := solve(f, utils.Verbose)
fmt.Println(r)
}
func solve(r io.Reader, verbose bool) int {
lines := utils.ReadLines(r)
maze := parseMaze(lines)
ch := mazeSolver(maze)
total := 0
for p := range ch {
if verbose {
fmt.Println(strings.Join(p, ","))
}
total += 1
}
return total
}
func parseMaze(lines []string) map[string][]string {
maze := make(map[string][]string)
for _, ln := range lines {
parts := strings.Split(ln, "-")
maze[parts[0]] = append(maze[parts[0]], parts[1])
maze[parts[1]] = append(maze[parts[1]], parts[0])
}
return maze
}
// Generate maze solutions and export them on channel
func mazeSolver(maze map[string][]string) <-chan []string {
ch := make(chan []string)
path := []string{"start"}
seen := make(map[string]int)
go func() {
mazeSolveRecursor(maze, &path, seen, 2, ch)
close(ch)
}()
return ch
}
func mazeSolveRecursor(maze map[string][]string, path *[]string, seen map[string]int, maxseen int, ch chan<- []string) {
current := (*path)[len(*path)-1]
maxallowed := maxseen
if current == strings.ToLower(current) {
if current == "start" {
maxallowed = 1
}
if seen[current] >= maxallowed {
// do not continue path
return
}
if seen[current]++; seen[current] == 2 {
maxseen = 1
}
}
if current == "end" {
// path complete! Send a copy back on the channel
complete := make([]string, len(*path))
copy(complete, *path)
ch <- complete
seen[current]--
return
}
nextpos := len(*path)
*path = append(*path, "") // place holder for next step
nextsteps := maze[current]
for _, room := range nextsteps {
(*path)[nextpos] = room
mazeSolveRecursor(maze, path, seen, maxseen, ch)
}
*path = (*path)[:nextpos]
seen[current]--
return
}