summaryrefslogtreecommitdiff
path: root/2024/go/src/day16/main.go
blob: a53a2882ca1db069a65adb3082c75b9ddb246b6f (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main

import (
	"container/heap"
	"fmt"
	"os"
	"strings"
)

func FileRead(path string) string {
	file, err := os.ReadFile(path)
	if err != nil {
		fmt.Println("Couldn't Read file: ", err)
	}
	return string(file)
}

type Grid = [][]byte

type Point struct {
	x int
	y int
}

func parseInput(data string) Grid {
	lines := strings.Split(data, "\n")

	var grid Grid
	for _, line := range lines {
		if len(line) > 0 {
			bytes := []byte(line)
			grid = append(grid, bytes)
		}
	}
	return grid
}

func printGrid(grid [][]byte) {
	for _, row := range grid {
		for _, cell := range row {
			fmt.Printf(string(cell))
		}
		fmt.Println()
	}
}

func copySlice(src []Point) []Point {
	dest := make([]Point, len(src))
	copy(dest, src)
	return dest
}

func findMin(arr []int) int {
	min := arr[0]
	for _, v := range arr[1:] {
		if v < min {
			min = v
		}
	}
	return min
}

type Direction struct {
	dx, dy int
}

type State struct {
	cost      int
	stepCount int
	pos       Point
	dir       Direction
}

type PriorityQueue []*State

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].cost < pq[j].cost
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Push(x interface{}) {
	item := x.(*State)
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func inBounds(x, y, rows, cols int, grid [][]byte) bool {
	return x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] != '#'
}

func findPosition(grid [][]byte, target byte) (Point, bool) {
	for i := range grid {
		for j := range grid[i] {
			if grid[i][j] == target {
				return Point{i, j}, true
			}
		}
	}
	return Point{}, false
}

func dijkstra(grid [][]byte, start Point, end Point) (int, int, []Point) { // Returns cost, step count, and path
	if start == end {
		return 0, 0, []Point{start}
	}
	var directions = [4]Direction{
		{1, 0},  // Down
		{0, 1},  // Right
		{-1, 0}, // Up
		{0, -1}, // Left
	}
	pq := &PriorityQueue{}
	heap.Init(pq)
	type Key struct {
		x, y, dx, dy int
	}
	minCost := make(map[Key]int)
	stepCounts := make(map[Key]int)
	prev := make(map[Key]Key)          // Track previous position for path reconstruction
	prevDir := make(map[Key]Direction) // Track previous direction

	heap.Push(pq, &State{cost: 0, stepCount: 0, pos: start, dir: Direction{0, 0}})

	for pq.Len() > 0 {
		current := heap.Pop(pq).(*State)
		cost := current.cost
		stepCount := current.stepCount
		pos := current.pos
		dir := current.dir
		key := Key{pos.x, pos.y, dir.dx, dir.dy}

		if existingCost, exists := minCost[key]; exists && cost >= existingCost {
			continue
		}

		minCost[key] = cost
		stepCounts[key] = stepCount

		if pos == end {
			// Reconstruct path
			path := []Point{end}
			currentKey := key

			for currentKey.x != start.x || currentKey.y != start.y {
				previousKey := prev[currentKey]
				path = append([]Point{{previousKey.x, previousKey.y}}, path...)
				currentKey = previousKey
			}

			return cost, stepCount, path
		}

		for _, d := range directions {
			nx, ny := pos.x+d.dx, pos.y+d.dy
			if inBounds(nx, ny, len(grid), len(grid[0]), grid) {
				var newCost int
				if dir == (Direction{0, 0}) || d == dir {
					newCost = cost + 1
				} else {
					newCost = cost + 1001
				}
				newStepCount := stepCount + 1
				newKey := Key{nx, ny, d.dx, d.dy}

				if existingCost, exists := minCost[newKey]; !exists || newCost < existingCost {
					heap.Push(pq, &State{cost: newCost, stepCount: newStepCount, pos: Point{nx, ny}, dir: d})
					prev[newKey] = key    // Store the previous position
					prevDir[newKey] = dir // Store the previous direction
				}
			}
		}
	}

	return 0, 0, nil // 'S' is not reachable
}

func solve_part_one(data string) int {
	maze := parseInput(data)
	start, _ := findPosition(maze, 'E')
	end, _ := findPosition(maze, 'S')
	cost, _, _ := dijkstra(maze, start, end)
	return cost
}

func solve_part_two(data string) int {
	maze := parseInput(data)
	start, _ := findPosition(maze, 'E')
	end, _ := findPosition(maze, 'S')
	bestCost, _, path := dijkstra(maze, start, end)
	uniquePoints := make(map[Point]struct{})
	for _, p := range path {
		uniquePoints[p] = struct{}{}
	}

	fmt.Println(bestCost)

	for i := range maze {
		for j := range maze[i] {
			currentPoint := Point{i, j}
			_, exists := uniquePoints[currentPoint]
			if exists {
				continue
			}
			costCurToStart, _, pathStart := dijkstra(maze, start, currentPoint)
			costCurToEnd, _, pathEnd := dijkstra(maze, currentPoint, end)
			if costCurToStart+costCurToEnd+1000 == bestCost || costCurToStart+costCurToEnd == bestCost {
				for _, p := range pathStart {
					uniquePoints[p] = struct{}{}
				}
				for _, p := range pathEnd {
					uniquePoints[