Skip to content

Commit 8d80636

Browse files
committed
Count reachable
1 parent 608df8b commit 8d80636

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

21.swift

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ struct Grid {
1616
init(map: Map) {
1717
self.map = map
1818
self.start = Grid.findStart(map)
19-
self.max = Coordinate(x: map[0].count, y: map.count)
19+
self.max = Coordinate(x: map[0].count - 1, y: map.count - 1)
2020
}
2121

2222
static func findStart(_ map: Map) -> Coordinate {
@@ -61,10 +61,35 @@ func readInput() -> Grid {
6161
return Grid(map: map)
6262
}
6363

64-
func bfs(_ map: Map) -> Int {
64+
func bfs(grid: Grid, maxStep: Int) -> Int {
6565
var visited: Set<Coordinate> = Set()
66-
return 0
66+
67+
var pending = [(grid.start, 0)]
68+
var pi = 0
69+
70+
while pi < pending.count {
71+
let (c, step) = pending[pi]
72+
pi += 1
73+
74+
if !visited.insert(c).inserted {
75+
continue
76+
}
77+
78+
if step == maxStep {
79+
continue
80+
}
81+
82+
for n in grid.neighbours(of: c) {
83+
if !visited.contains(n) {
84+
pending.append((n, step + 1))
85+
}
86+
}
87+
}
88+
89+
return visited.count
6790
}
6891

6992
let grid = readInput()
93+
let c = bfs(grid: grid, maxStep: 64)
7094
print(grid)
95+
print(c)

0 commit comments

Comments
 (0)