From 89800584f4351a43dcbb92446985b89d05665a0f Mon Sep 17 00:00:00 2001 From: Dory Date: Wed, 18 Dec 2024 12:34:43 -0800 Subject: [PATCH] bfs and binary search --- day18/d18p2.swift | 49 ++++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/day18/d18p2.swift b/day18/d18p2.swift index 55285d1..b630d6a 100644 --- a/day18/d18p2.swift +++ b/day18/d18p2.swift @@ -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 = [start] + var seen: Set = [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.. 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..