Skip to content

Instantly share code, notes, and snippets.

@pavlov99
Created January 27, 2016 06:30
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 pavlov99/568d6f38271dc8f93f2a to your computer and use it in GitHub Desktop.
Save pavlov99/568d6f38271dc8f93f2a to your computer and use it in GitHub Desktop.
Graph BFS DFS
class Graph[T] {
type Vertex = T
type GraphMap = Map[Vertex,List[Vertex]]
var g:GraphMap = Map()
def BFS(start: Vertex): List[List[Vertex]] = {
def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {
val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct
if (newNeighbors.isEmpty)
visited
else
BFS0(newNeighbors, newNeighbors :: visited)
}
BFS0(List(start),List(List(start))).reverse
}
def DFS(start: Vertex): List[Vertex] = {
def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {
if (visited.contains(v))
visited
else {
val neighbours:List[Vertex] = g(v) filterNot visited.contains
neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))
}
}
DFS0(start,List()).reverse
}
}
var intGraph = new Graph[Int]
intGraph.g = Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3))
intGraph.BFS(1)
intGraph.BFS(2)
intGraph.DFS(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment