Skip to content

Commit 936c040

Browse files
committed
Try alternative tack of modifying the grid itself
1 parent 8ee28e0 commit 936c040

File tree

1 file changed

+61
-7
lines changed

1 file changed

+61
-7
lines changed

21.swift

+61-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
// The Garden of Forking Paths
2-
//
3-
// Part 1: Do a BFS to find all reachable nodes within 64 steps.
42

53
typealias Map = [[Character]]
64

@@ -9,7 +7,7 @@ struct Coordinate: Hashable {
97
}
108

119
struct Grid {
12-
let map: Map
10+
var map: Map
1311
let start: Coordinate
1412
let max: Coordinate
1513

@@ -45,6 +43,41 @@ struct Grid {
4543
[(c.x - 1, c.y), (c.x + 1, c.y), (c.x, c.y - 1), (c.x, c.y + 1)]
4644
.map { Coordinate(x: $0, y: $1) }
4745
}
46+
47+
func coordinates() -> [Coordinate] {
48+
var result: [Coordinate] = []
49+
for y in 0...max.y {
50+
for x in 0...max.x {
51+
result.append(Coordinate(x: x, y: y))
52+
}
53+
}
54+
return result
55+
}
56+
57+
mutating func move() {
58+
func isOccupied(_ c: Character) -> Bool {
59+
c == "O" || c == "S"
60+
}
61+
62+
let prevMap = map
63+
let cs = coordinates()
64+
for c in cs {
65+
if isOccupied(map[c.y][c.x]) {
66+
map[c.y][c.x] = "."
67+
}
68+
}
69+
for c in cs {
70+
if isOccupied(prevMap[c.y][c.x]) {
71+
for n in neighbours(of: c) {
72+
map[n.y][n.x] = "O"
73+
}
74+
}
75+
}
76+
}
77+
78+
var reachable: Int {
79+
map.reduce(0, { $1.reduce($0, { $0 + ($1 == "O" ? 1 : 0) })})
80+
}
4881
}
4982

5083
extension Grid: CustomStringConvertible {
@@ -84,7 +117,28 @@ func bfs(grid: Grid, maxStep: Int) -> Int {
84117
return lastCells.count
85118
}
86119

87-
let grid = readInput()
88-
let c = bfs(grid: grid, maxStep: 6)
89-
// print(grid)
90-
print(c)
120+
func move(grid: inout Grid, steps: Int) {
121+
for s in 1...steps {
122+
grid.move()
123+
if verbose > 0 {
124+
print("after step \(s) we reached \(grid.reachable) cells")
125+
print(grid)
126+
print("")
127+
}
128+
}
129+
}
130+
131+
let verbose = switch CommandLine.arguments.last {
132+
case "-v": 1
133+
case "-vv": 2
134+
default: 0
135+
}
136+
137+
var grid = readInput()
138+
move(grid: &grid, steps: 6)
139+
let p1 = grid.reachable
140+
print(p1)
141+
142+
// let c = bfs(grid: grid, maxStep: 16)
143+
144+
// print(c)

0 commit comments

Comments
 (0)