From e35da0cd558dc1fe5af2faa0089ac6ebb45c5bfa Mon Sep 17 00:00:00 2001 From: Dory Date: Wed, 18 Dec 2024 00:36:14 -0800 Subject: [PATCH] replacing dijkstra with a* didn't speed it up... --- day18/d18p2.swift | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/day18/d18p2.swift b/day18/d18p2.swift index 38631b3..55285d1 100644 --- a/day18/d18p2.swift +++ b/day18/d18p2.swift @@ -23,29 +23,34 @@ struct Map : CustomStringConvertible { let top = " \u{001B}[4m" + (0.. Int? { + 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: Set = [start] - q.insert((start, 0)) - while let (cell, cost) = q.pop() { + var seen: [Coord: Int] = [start: 0] + q.insert((start, heur(start, end))) + while let (cell, _) = q.pop() { if cell == end { - return cost + return seen[cell] } [(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 { !seen.contains($0) } .filter { !walls.contains($0) } - .forEach { neighbor in - seen.insert(neighbor) - q.insert((neighbor, cost + 1)) + .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))) + } } } return nil @@ -58,9 +63,10 @@ struct AoC { let bytes = try readInput(CommandLine.arguments[1]) let w = Int(CommandLine.arguments[2]) ?? 71 let h = Int(CommandLine.arguments[3]) ?? 71 - for limit in 1024..