use a heap for marginally faster execution
This commit is contained in:
@@ -58,7 +58,7 @@ struct Maze : CustomStringConvertible {
|
||||
let s: [[String]] = walls.enumerated().map { i, r in
|
||||
[String(format: "%3d ", i)] + r.map { $0 ? "██" : " " }
|
||||
}
|
||||
print(" 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4")
|
||||
print(" " + (0..<w).map { " \($0 % 10)" }.joined())
|
||||
return s.map { $0.joined() }.joined(separator: "\n")
|
||||
}
|
||||
init(fromFile f: String) throws {
|
||||
@@ -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("minCost: \(maze.search())")
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user