Use ArrayDeque for BFS implementation (#2529)

This commit is contained in:
Väinö Mäkelä
2020-04-27 22:57:32 +03:00
committed by GitHub
parent 6e03910097
commit c4f1e0f15d

View File

@ -1,10 +1,13 @@
package com.unciv.logic.map package com.unciv.logic.map
// Kotlin's ArrayDeque is experimental
import java.util.ArrayDeque
/** /**
* Defines intermediate steps of a breadth-first search, for use in either get shortest path or get onnected tiles. * Defines intermediate steps of a breadth-first search, for use in either get shortest path or get onnected tiles.
*/ */
class BFS(val startingPoint: TileInfo, val predicate : (TileInfo) -> Boolean){ class BFS(val startingPoint: TileInfo, val predicate : (TileInfo) -> Boolean){
var tilesToCheck = ArrayList<TileInfo>() var tilesToCheck = ArrayDeque<TileInfo>()
/** each tile reached points to its parent tile, where we got to it from */ /** each tile reached points to its parent tile, where we got to it from */
val tilesReached = HashMap<TileInfo, TileInfo>() val tilesReached = HashMap<TileInfo, TileInfo>()
@ -25,16 +28,13 @@ class BFS(val startingPoint: TileInfo, val predicate : (TileInfo) -> Boolean){
} }
fun nextStep(){ fun nextStep(){
val newTilesToCheck = ArrayList<TileInfo>() val current = tilesToCheck.remove()
for(tileInfo in tilesToCheck){ for(neighbor in current.neighbors){
for(neighbor in tileInfo.neighbors){ if(predicate(neighbor) && !tilesReached.containsKey(neighbor)){
if(predicate(neighbor) && !tilesReached.containsKey(neighbor)){ tilesReached[neighbor] = current
tilesReached[neighbor] = tileInfo tilesToCheck.add(neighbor)
newTilesToCheck.add(neighbor)
}
} }
} }
tilesToCheck = newTilesToCheck
} }
fun getPathTo(destination: TileInfo): ArrayList<TileInfo> { fun getPathTo(destination: TileInfo): ArrayList<TileInfo> {