Skip to content

Instantly share code, notes, and snippets.

@treadstone90
Created October 23, 2014 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treadstone90/a7ca1bd9e54e42b56ad4 to your computer and use it in GitHub Desktop.
Save treadstone90/a7ca1bd9e54e42b56ad4 to your computer and use it in GitHub Desktop.
Blog BFS top down
class BFS(g: Graph) {
val parent = ArrayBuffer.fill(g.numberVertices)(-1).toArray
def bfs(source: Int, updater: (Seq[Int], Array[Int]) => Seq[Int]) = {
var frontier = Seq(source)
parent(source) = -2
while (!frontier.isEmpty) {
frontier = updater(frontier, parent)
}
}
}
trait TopDownUpdater extends FrontierUpdater {
def update(frontier: Seq[Int], parents: Array[Int]): Seq[Int] = {
val next = ArrayBuffer[Int]()
frontier.foreach{ node =>
graph.getNeighbors(node).filter(parents(_) == -1).foreach { neighbor =>
next += neighbor
parents(neighbor) = node
}
}
next
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment