-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (88 loc) · 2.05 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 (
"bufio"
"fmt"
"os"
)
var island = []string{}
var islandHeight int
var islandWidth int
func main() {
file, _ := os.Open("input.txt")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
island = append(island, scanner.Text())
}
islandHeight = len(island)
islandWidth = len(island[0])
answer1 := 0
answer2 := 0
for y, line := range island {
for x, char := range line {
// Find all zeros
if char != 48 {
continue
}
// Part one
trailhead := fmt.Sprintf("%d-%d", y, x)
peaks := make(map[string]bool)
searchPart1(y, x, trailhead, peaks)
answer1 += len(peaks)
// Part two
var trails *int = new(int)
*trails = 0
searchPart2(y, x, trails)
answer2 += *trails
}
}
fmt.Printf("Answer part 1: %d\n", answer1)
fmt.Printf("Answer part 2: %d\n", answer2)
}
func searchPart2(y int, x int, trails *int) {
currentValue := island[y][x]
searchValue := currentValue + 1
if currentValue == 57 {
*trails++
return
}
// Travel above
if y-1 >= 0 && island[y-1][x] == searchValue {
searchPart2(y-1, x, trails)
}
// Travel right
if x+1 < islandWidth && island[y][x+1] == searchValue {
searchPart2(y, x+1, trails)
}
// Travel below
if y+1 < islandHeight && island[y+1][x] == searchValue {
searchPart2(y+1, x, trails)
}
// Travel left
if x-1 >= 0 && island[y][x-1] == searchValue {
searchPart2(y, x-1, trails)
}
}
func searchPart1(y int, x int, trailhead string, peaks map[string]bool) {
currentValue := island[y][x]
searchValue := currentValue + 1
if currentValue == 57 {
peaks[fmt.Sprintf("%s-%d-%d", trailhead, y, x)] = true
return
}
// Travel above
if y-1 >= 0 && island[y-1][x] == searchValue {
searchPart1(y-1, x, trailhead, peaks)
}
// Travel right
if x+1 < islandWidth && island[y][x+1] == searchValue {
searchPart1(y, x+1, trailhead, peaks)
}
// Travel below
if y+1 < islandHeight && island[y+1][x] == searchValue {
searchPart1(y+1, x, trailhead, peaks)
}
// Travel left
if x-1 >= 0 && island[y][x-1] == searchValue {
searchPart1(y, x-1, trailhead, peaks)
}
}