use a heap for marginally faster execution

This commit is contained in:
2024-12-16 09:53:09 -08:00
parent 9bb5d1f769
commit f9ff6d9501
3 changed files with 97 additions and 39 deletions

View File

@@ -111,10 +111,10 @@ struct Maze : CustomStringConvertible {
let edges = graph()
// edges.forEach { k, v in print(" - \(k): \(v)") }
var q: [CellCost] = [(cell: start, cost: 0)]
var q = Heap<CellCost>(comparator: { $0.cost < $1.cost })
q.insert((cell: start, cost: 0))
var visited: [Cell:Int] = [:]
while !q.isEmpty {
let e = q.removeLast()
while let e = q.pop() {
if let node = edges[e.cell] {
for (cell, cost) in node {
if let prevCost = visited[cell] {
@@ -123,7 +123,7 @@ struct Maze : CustomStringConvertible {
}
}
visited[cell] = e.cost + cost
q.append((cell: cell, cost: e.cost + cost))
q.insert((cell: cell, cost: e.cost + cost))
}
}
}
@@ -131,6 +131,12 @@ struct Maze : CustomStringConvertible {
}
}
let maze = try Maze(fromFile: CommandLine.arguments[1])
// print(maze)
print(maze.search())
@main
struct AoC {
static func main() throws {
let maze = try Maze(fromFile: CommandLine.arguments[1])
// print(maze)
print(maze.search())
}
}