Caching neighbours
This commit is contained in:
parent
3dd2188f11
commit
93f1c73fbf
@ -38,6 +38,8 @@ struct Field:Sequence, IteratorProtocol {
|
||||
let numCols: Int
|
||||
let numRows: Int
|
||||
|
||||
var neighbors = [Coord:[Coord]]()
|
||||
|
||||
var current: Coord? = Coord(row: 0, col: 0)
|
||||
|
||||
init(numbers: [[Int]]) {
|
||||
@ -46,13 +48,15 @@ struct Field:Sequence, IteratorProtocol {
|
||||
numRows = numbers.count
|
||||
}
|
||||
|
||||
func getNeighborsCoordsFor(coord: Coord) -> [Coord] {
|
||||
return [coord.getAbove(), coord.getRight(), coord.getBelow(), coord.getLeft()]
|
||||
mutating func getNeighborsCoordsFor(coord: Coord) -> [Coord] {
|
||||
let n = neighbors[coord] ?? [coord.getAbove(), coord.getRight(), coord.getBelow(), coord.getLeft()]
|
||||
.compactMap { $0 }
|
||||
.filter { $0.row < numRows && $0.col < numCols }
|
||||
neighbors[coord] = n
|
||||
return n
|
||||
}
|
||||
|
||||
func isLowPointAt(coord: Coord) -> Bool {
|
||||
mutating func isLowPointAt(coord: Coord) -> Bool {
|
||||
let value = self[coord]
|
||||
return getNeighborsCoordsFor(coord: coord)
|
||||
.map { numbers[$0.row][$0.col] }
|
||||
|
Loading…
Reference in New Issue
Block a user