Skip to content

Commit 023ba87

Browse files
committed
Another shortest path impl
1 parent eab7f90 commit 023ba87

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

17.wip.swift

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,54 @@ func readInput() -> Grid {
1717
x += 1
1818
}
1919
y += 1
20+
}
21+
return Grid(items: items, lastNode: .init(x: x - 1, y: y - 1))
22+
}
23+
24+
func shortestPath(grid: Grid) -> Int? {
25+
let startNode = Node(x: 0, y: 0)
26+
func isEnd(node: Node) -> Bool { node == grid.lastNode }
2027

28+
var dist: [Node: Int] = [startNode: 0]
29+
var seen: Set<Node> = Set()
30+
//var invDist: [Int: [Node]] = []
31+
//var minDist = 0
32+
33+
func popNearest() -> (Node, Int)? {
34+
var u: Node?
35+
var du: Int = .max
36+
for (v, dv) in dist {
37+
if dv < du && !seen.contains(v) {
38+
u = v
39+
du = dv
40+
}
41+
}
42+
if let u { return (u, du) }
43+
return nil
2144
}
22-
return Grid(items: items, lastNode: .init(x: x, y: y))
45+
46+
while let (u, du) = popNearest() {
47+
if !seen.insert(u).inserted { continue }
48+
if isEnd(node: u) { return du }
49+
for v in neighbours(grid: grid, node: u) {
50+
let d = grid.items[v]!
51+
let dv = dist[v] ?? .max
52+
if du + d < dv {
53+
dist[v] = du + d
54+
}
55+
}
56+
}
57+
58+
return nil
59+
}
60+
61+
func neighbours(grid: Grid, node: Node) -> [Node] {
62+
let (x, y) = (node.x, node.y)
63+
return [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
64+
.map { Node(x: $0.0, y: $0.1) }
65+
.filter { grid.items[$0] != nil }
2366
}
2467

2568
let grid = readInput()
26-
print(grid)
69+
let sp = shortestPath(grid: grid)
70+
print(sp ?? 0)

0 commit comments

Comments
 (0)