1
1
// The Garden of Forking Paths
2
- //
3
- // Part 1: Do a BFS to find all reachable nodes within 64 steps.
4
2
5
3
typealias Map = [ [ Character ] ]
6
4
@@ -9,7 +7,7 @@ struct Coordinate: Hashable {
9
7
}
10
8
11
9
struct Grid {
12
- let map : Map
10
+ var map : Map
13
11
let start : Coordinate
14
12
let max : Coordinate
15
13
@@ -45,6 +43,41 @@ struct Grid {
45
43
[ ( c. x - 1 , c. y) , ( c. x + 1 , c. y) , ( c. x, c. y - 1 ) , ( c. x, c. y + 1 ) ]
46
44
. map { Coordinate ( x: $0, y: $1) }
47
45
}
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
+ }
48
81
}
49
82
50
83
extension Grid : CustomStringConvertible {
@@ -84,7 +117,28 @@ func bfs(grid: Grid, maxStep: Int) -> Int {
84
117
return lastCells. count
85
118
}
86
119
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