bfs and binary search

This commit is contained in:
2024-12-18 12:34:43 -08:00
parent e35da0cd55
commit 89800584f4

View File

@@ -33,27 +33,25 @@ struct Map : CustomStringConvertible {
func heur(_ a: Coord, _ b: Coord) -> Int {
return abs(a.x - b.x) + abs(a.y - b.y)
}
func astar(from start: Coord, to end: Coord) -> Int? {
var q = Heap<(Coord, Int)>(comparator: { l, r in l.1 < r.1 })
var seen: [Coord: Int] = [start: 0]
q.insert((start, heur(start, end)))
while let (cell, _) = q.pop() {
func bfs(from start: Coord, to end: Coord) -> Bool {
var q: Set<Coord> = [start]
var seen: Set<Coord> = [start]
while !q.isEmpty {
let cell = q.removeFirst()
if cell == end {
return seen[cell]
return true
}
[(0, -1), (0, 1), (-1, 0), (1, 0)].map { dy, dx in
Coord(x: cell.x + dx, y: cell.y + dy)}
.filter { c in c.x >= 0 && c.y >= 0 && c.x < w && c.y < h }
.filter { !walls.contains($0) }
.filter { !seen.contains($0) }
.forEach { nb in
let newCost = seen[cell]! + 1
if seen[nb, default: w*h] > newCost {
seen[nb] = newCost
q.insert((nb, newCost + heur(nb, end)))
}
seen.insert(nb)
q.insert(nb)
}
}
return nil
return false
}
}
@@ -64,19 +62,26 @@ struct AoC {
let w = Int(CommandLine.arguments[2]) ?? 71
let h = Int(CommandLine.arguments[3]) ?? 71
let startLimit = Int(CommandLine.arguments[4]) ?? 1024
for limit in startLimit..<bytes.count {
let map = Map(walls: Set(bytes.prefix(limit)), w: w, h: h)
if let cost = map.astar(
from: Coord(x: 0, y: 0),
to: Coord(x: map.w - 1, y: map.h - 1)
) {
print("\(limit): \(cost)")
var range = Array(startLimit..<bytes.count)
while range.count > 1 {
let center = range.count/2
print("Trying \(range[center])...", terminator: "")
let map = Map(walls: Set(bytes.prefix(range[center])), w: w, h: h)
if map.bfs(from: Coord(x: 0, y: 0), to: Coord(x: w-1, y: h-1)) {
print(" works")
range = Array(range[center+1..<range.count])
} else {
print(map)
print("found byte \(limit-1): \(bytes[limit-1])")
return
print(" blocked")
range = Array(range[0..<center])
}
}
let map = Map(walls: Set(bytes.prefix(range[0])), w: w, h: h)
print(map)
if map.bfs(from: Coord(x: 0, y: 0), to: Coord(x: w-1, y: h-1)) {
print("at \(range[0]): \(bytes[range[0]])")
} else {
print("at \(range[0] + 1): \(bytes[range[0] + 1])")
}
}
}