-
-
Save zodsoft/05d3f76f857518af5e6b66587863b3ae to your computer and use it in GitHub Desktop.
bfs/dfs implementation of a graph in Scala 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.annotation.tailrec | |
class Graph[A](m: Map[A, Set[A]]): | |
type Vertex = A | |
type GraphMap = Map[Vertex, Set[Vertex]] | |
private def neighbors(v: Vertex): List[Vertex] = | |
m.get(v).map(_.toList).getOrElse(List.empty[Vertex]) | |
def search(start: Vertex, end: Vertex): Boolean = | |
@tailrec | |
def bfs(toVisit: List[Vertex], visited: List[Vertex]): Boolean = | |
toVisit.headOption match | |
case Some(current) if (current == end) => true | |
case Some(current) if visited.exists(_ == current) => bfs(toVisit.tail, visited) | |
case Some(current) => | |
val ns: List[Vertex] = neighbors(current) | |
val newToVisit: List[Vertex] = toVisit.tail ++ ns | |
bfs(newToVisit, current::visited) | |
case None => false | |
@tailrec | |
def dfs(toVisit: List[Vertex], visited: List[Vertex]): Boolean = | |
toVisit.headOption match | |
case Some(current) if (current == end) => true | |
case Some(current) if visited.exists(_ == current) => dfs(toVisit.tail, visited) | |
case Some(current) => | |
val ns: List[Vertex] = neighbors(current) | |
val newToVisit: List[Vertex] = ns ++ toVisit.tail | |
dfs(newToVisit, current::visited) | |
case None => false | |
bfs(List(start), List.empty[Vertex]) && | |
dfs(List(start), List.empty[Vertex]) | |
object Main: | |
def main(args: Array[String]): Unit = | |
val m = Map(("A" -> Set("B", "C")), | |
("B" -> Set("D", "E")), | |
("C" -> Set("F", "G")), | |
) | |
val path = Graph(m).search("A", "G") | |
println(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment