Created
January 27, 2016 06:30
-
-
Save pavlov99/568d6f38271dc8f93f2a to your computer and use it in GitHub Desktop.
Graph BFS DFS
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
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