diff --git a/Data Structures/Scala/bfs.scala b/Data Structures/Scala/bfs.scala new file mode 100644 index 0000000..2e027cd --- /dev/null +++ b/Data Structures/Scala/bfs.scala @@ -0,0 +1,17 @@ +def bfs(graph: Map[Int, List[Int]], start: Int): List[Int] = { + var visited = Set.empty[Int] + var queue = List(start) + var result = List.empty[Int] + + while (queue.nonEmpty) { + val node = queue.head + queue = queue.tail + if (!visited(node)) { + visited += node + result = node :: result + queue ++= graph(node).filterNot(visited) + } + } + + result.reverse +}