Skip to content

Commit 608df8b

Browse files
committed
Find neighbours
1 parent ab8555f commit 608df8b

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

21.swift

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
// Part 1: Do a BFS to find all reachable nodes within 64 steps.
44

55
typealias Map = [[Character]]
6-
typealias Coordinate = (x: Int, y: Int)
6+
7+
struct Coordinate: Hashable {
8+
let x, y: Int
9+
}
710

811
struct Grid {
912
let map: Map
@@ -13,20 +16,34 @@ struct Grid {
1316
init(map: Map) {
1417
self.map = map
1518
self.start = Grid.findStart(map)
16-
self.max = (map[0].count, map.count)
19+
self.max = Coordinate(x: map[0].count, y: map.count)
1720
}
1821

1922
static func findStart(_ map: Map) -> Coordinate {
2023
for (y, row) in map.enumerated() {
2124
for (x, c) in row.enumerated() {
22-
if c == "S" { return (x, y) }
25+
if c == "S" { return Coordinate(x: x, y: y) }
2326
}
2427
}
2528
fatalError()
2629
}
2730

31+
func at(_ c: Coordinate) -> Character {
32+
map[c.y][c.x]
33+
}
34+
2835
func neighbours(of c: Coordinate) -> [Coordinate] {
29-
return []
36+
potentialNeighbours(c).filter { inBounds($0) && at($0) != "#" }
37+
}
38+
39+
func inBounds(_ c: Coordinate) -> Bool {
40+
c.x >= 0 && c.x <= max.x &&
41+
c.y >= 0 && c.y <= max.y
42+
}
43+
44+
func potentialNeighbours(_ c: Coordinate) -> [Coordinate] {
45+
[(c.x - 1, c.y), (c.x + 1, c.y), (c.x, c.y - 1), (c.x, c.y + 1)]
46+
.map { Coordinate(x: $0, y: $1) }
3047
}
3148
}
3249

@@ -44,9 +61,10 @@ func readInput() -> Grid {
4461
return Grid(map: map)
4562
}
4663

47-
// func bfs(_ map: Map) -> Int {
48-
// var visited: Set
49-
// }
64+
func bfs(_ map: Map) -> Int {
65+
var visited: Set<Coordinate> = Set()
66+
return 0
67+
}
5068

5169
let grid = readInput()
5270
print(grid)

0 commit comments

Comments
 (0)