Skip to content

Commit c61d436

Browse files
committed
Solution for 2024, day 18
1 parent 6583225 commit c61d436

File tree

4 files changed

+118
-0
lines changed

4 files changed

+118
-0
lines changed

2024/18/Makefile

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
input:
2+
http "https://adventofcode.com/2024/day/18/input" "Cookie:session=${AOC_SESSION};" >input
3+
4+
main1:
5+
go build -o main1 main1.go common.go
6+
7+
main2:
8+
go build -o main2 main2.go common.go
9+
10+
.PHONY: run1 run2 clean
11+
12+
run1: main1 input
13+
./main1 <input
14+
15+
run2: main2 input
16+
./main2 <input
17+
18+
clean:
19+
rm -f main1 main2 input

2024/18/common.go

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"os"
6+
"strconv"
7+
"strings"
8+
)
9+
10+
const Size = 70
11+
12+
type P struct{ x, y int }
13+
14+
var (
15+
Start = P{0, 0}
16+
Goal = P{Size, Size}
17+
Delta = []P{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
18+
)
19+
20+
func parseInput() []P {
21+
var m []P
22+
scanner := bufio.NewScanner(os.Stdin)
23+
for i := 0; scanner.Scan(); i++ {
24+
ff := strings.Split(scanner.Text(), ",")
25+
x, _ := strconv.Atoi(ff[0])
26+
y, _ := strconv.Atoi(ff[1])
27+
m = append(m, P{x, y})
28+
}
29+
return m
30+
}
31+
32+
func BFS(corrupted map[P]struct{}) []P {
33+
queue := []P{Start}
34+
visited := map[P]struct{}{Start: {}}
35+
parent := map[P]P{}
36+
37+
for len(queue) > 0 {
38+
var curr P
39+
curr, queue = queue[0], queue[1:]
40+
41+
if curr == Goal {
42+
var path []P
43+
for p := Goal; p != Start; p = parent[p] {
44+
path = append(path, p)
45+
}
46+
return path
47+
}
48+
49+
for _, d := range Delta {
50+
n := P{curr.x + d.x, curr.y + d.y}
51+
52+
if n.x < 0 || n.x > Size || n.y < 0 || n.y > Size {
53+
continue
54+
}
55+
56+
if _, ok := corrupted[n]; ok {
57+
continue
58+
}
59+
60+
if _, ok := visited[n]; !ok {
61+
visited[n] = struct{}{}
62+
parent[n] = curr
63+
queue = append(queue, n)
64+
}
65+
}
66+
}
67+
68+
return nil
69+
}

2024/18/main1.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
bytes := parseInput()
7+
8+
corrupted := map[P]struct{}{}
9+
for _, p := range bytes[:1024] {
10+
corrupted[p] = struct{}{}
11+
}
12+
13+
fmt.Println(len(BFS(corrupted)))
14+
}

2024/18/main2.go

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
bytes := parseInput()
7+
8+
corrupted := map[P]struct{}{}
9+
for _, p := range bytes {
10+
corrupted[p] = struct{}{}
11+
if path := BFS(corrupted); path == nil {
12+
fmt.Printf("%d,%d\n", p.x, p.y)
13+
return
14+
}
15+
}
16+
}

0 commit comments

Comments
 (0)