Caching neighbours

This commit is contained in:
Max Nuding 2021-12-09 20:01:26 +01:00
parent 3dd2188f11
commit 93f1c73fbf
Signed by: phlaym
GPG Key ID: A06651BAB6777237

View File

@ -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] }