Skip to content

Instantly share code, notes, and snippets.

@zodsoft
Forked from FreddieSanchez/Graph.scala
Created June 13, 2022 14:50
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 zodsoft/05d3f76f857518af5e6b66587863b3ae to your computer and use it in GitHub Desktop.
Save zodsoft/05d3f76f857518af5e6b66587863b3ae to your computer and use it in GitHub Desktop.
bfs/dfs implementation of a graph in Scala 3
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