summaryrefslogtreecommitdiff
path: root/day20/main.go
blob: 3c5921ead0fa005cdeee6b3dee2104d17f0fe4e3 (plain)
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
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"slices"
	"strings"
)

func main() {
	fmt.Println(part1(readData("example.txt")))
	fmt.Println(1358)
	fmt.Println(part1(readData("data.txt")))
}

func IntAbs(x int) int {
	if x >= 0 {
		return x
	} else {
		return -x
	}
}

func part1(maze [][]byte) (score1, score2 int) {
	startX, startY := findInMaze(maze, 'S')
	endX, endY := findInMaze(maze, 'E')
	distMap := buildDistMap(maze, startX, startY, endX, endY)

	dirs := [][2]int{}
	for dy := -20; dy <= 20; dy++ {
		for dx := -20; dx <= 20; dx++ {
			d := IntAbs(dx) + IntAbs(dy)
			if d >= 1 && d <= 20 {
				dirs = append(dirs, [2]int{dx, dy})
			}
		}
	}

	x, y := startX, startY
	for x != endX || y != endY {
		distNow := distMap[y][x]
		xNext, yNext := x, y
		for _, dir := range dirs {
			x2, y2 := x+dir[0], y+dir[1]
			dist := IntAbs(dir[0]) + IntAbs(dir[1])

			if dist == 1 && maze[y2][x2] != '#' && distMap[y2][x2] > distNow {
				xNext, yNext = x2, y2
			}

			if dist > 1 && x2 >= 0 && y2 >= 0 && y2 < len(maze) && x2 < len(maze[y2]) && distMap[y2][x2] > distNow && maze[y2][x2] != '#' {
				saved := distMap[y2][x2] - distNow - dist
				if dist == 2 && saved >= 100 {
					score1++
				}
				if saved >= 100 {
					score2++
				}
			}
		}
		x, y = xNext, yNext
	}

	return
}

func buildDistMap(maze [][]byte, x, y int, endX, endY int) (distMap [][]int) {
	distMap = make([][]int, len(maze))
	for y, _ := range distMap {
		distMap[y] = make([]int, len(maze[0]))
		for x := range distMap[y] {
			distMap[y][x] = math.MaxInt
		}
	}

	distMap[y][x] = 0
	var dirs = [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}

	for x != endX || y != endY {
		for _, dir := range dirs {
			x2, y2 := x+dir[0], y+dir[1]
			if maze[y2][x2] != '#' && distMap[y2][x2] == math.MaxInt {
				distMap[y2][x2] = distMap[y][x] + 1
				x, y = x2, y2
				break
			}
		}
	}

	return
}

func findInMaze(maze [][]byte, needle byte) (x, y int) {
	for y, line := range maze {
		if x := slices.Index(line, needle); x >= 0 {
			return x, y
		}
	}
	panic("not found")
}

func readData(fileName string) (maze [][]byte) {
	fp, _ := os.Open(fileName)
	scanner := bufio.NewScanner(fp)
	for scanner.Scan() {
		maze = append(maze, []byte(strings.TrimSpace(scanner.Text())))
	}
	return
}