|
1 | 1 | package main
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
4 | 5 | "github.com/terminalnode/adventofcode2024/common"
|
| 6 | + "github.com/terminalnode/adventofcode2024/common/util" |
| 7 | + "strings" |
5 | 8 | )
|
6 | 9 |
|
7 | 10 | func main() {
|
8 |
| - common.Setup(10, nil, nil) |
| 11 | + common.Setup(10, part1, nil) |
| 12 | +} |
| 13 | + |
| 14 | +func part1( |
| 15 | + input string, |
| 16 | +) string { |
| 17 | + topo := parseTopographicMap(input) |
| 18 | + |
| 19 | + out := 0 |
| 20 | + for y := 0; y < len(topo); y++ { |
| 21 | + row := topo[y] |
| 22 | + for x := 0; x < len(row); x++ { |
| 23 | + value := topo[y][x] |
| 24 | + if value != 0 { |
| 25 | + continue |
| 26 | + } |
| 27 | + |
| 28 | + nineMap := make(map[string]bool) |
| 29 | + buildMapForPart1(topo, nineMap, util.Coordinate{X: x, Y: y}, -1) |
| 30 | + out += len(nineMap) |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return fmt.Sprintf("Number of trails: %d", out) |
| 35 | +} |
| 36 | + |
| 37 | +func parseTopographicMap( |
| 38 | + input string, |
| 39 | +) [][]int { |
| 40 | + lines := strings.Split(input, "\n") |
| 41 | + out := make([][]int, len(lines)) |
| 42 | + for y, row := range lines { |
| 43 | + out[y] = make([]int, len(row)) |
| 44 | + for x, char := range row { |
| 45 | + digit := int(char) - '0' |
| 46 | + out[y][x] = digit |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return out |
| 51 | +} |
| 52 | + |
| 53 | +func buildMapForPart1( |
| 54 | + topographicMap [][]int, |
| 55 | + nineMap map[string]bool, |
| 56 | + position util.Coordinate, |
| 57 | + prevValue int, |
| 58 | +) { |
| 59 | + if !util.In2DArray(position, topographicMap) { |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + value := topographicMap[position.Y][position.X] |
| 64 | + if value != prevValue+1 { |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + if value == 9 { |
| 69 | + k := fmt.Sprintf("%v", position) |
| 70 | + nineMap[k] = true |
| 71 | + } else { |
| 72 | + cs := []util.Coordinate{ |
| 73 | + position.North(), |
| 74 | + position.East(), |
| 75 | + position.South(), |
| 76 | + position.West(), |
| 77 | + } |
| 78 | + for _, newPos := range cs { |
| 79 | + buildMapForPart1(topographicMap, nineMap, newPos, value) |
| 80 | + } |
| 81 | + } |
9 | 82 | }
|
0 commit comments