Skip to content

Commit f1ae9da

Browse files
committed
2022 day 24 part 2
1 parent 154ac7c commit f1ae9da

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

aoc22.playground/Pages/Day24.xcplaygroundpage/Contents.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
import Foundation
44

55
part1()
6+
part2()
67

78
//: [Next](@next)

aoc22.playground/Pages/Day24.xcplaygroundpage/Sources/Day24.swift

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,16 @@ func inputData() -> World {
129129
)
130130
}
131131

132-
func bfs(world: World) -> Int {
132+
func bfs(world: World, traversals: Int) -> Int {
133+
var goal = world.goal
134+
var start = world.start
133135
var canvas = world
134136
var queue = [Point]()
135-
queue.append(world.start)
137+
queue.append(start)
136138
var nextQueue = Set<Point>()
137139
var t = -1
138-
140+
var traversal = 1
141+
139142
while !(queue.isEmpty && nextQueue.isEmpty) {
140143
if queue.isEmpty {
141144
queue = Array(nextQueue.sorted(by: { world.goal.manhattan($0) < world.goal.manhattan($1)}).prefix(2000))
@@ -144,8 +147,23 @@ func bfs(world: World) -> Int {
144147
t += 1
145148
}
146149
let cur = queue.remove(at: 0)
147-
if world.goal == cur {
148-
return t
150+
if goal == cur {
151+
if traversal == traversals {
152+
return t
153+
}
154+
if 0 == traversal % 2 {
155+
goal = world.goal
156+
start = world.start
157+
} else {
158+
goal = world.start
159+
start = world.goal
160+
}
161+
traversal += 1
162+
queue = []
163+
queue.append(start)
164+
nextQueue = []
165+
canvas.step()
166+
t += 1
149167
}
150168
for n in cur.neighbors() where canvas.contains(n) {
151169
nextQueue.insert(n)
@@ -155,6 +173,9 @@ func bfs(world: World) -> Int {
155173
}
156174

157175
public func part1() -> Int {
158-
bfs(world: inputData())
176+
bfs(world: inputData(), traversals: 1)
159177
}
160178

179+
public func part2() -> Int {
180+
bfs(world: inputData(), traversals: 3)
181+
}

0 commit comments

Comments
 (0)