Skip to content

Instantly share code, notes, and snippets.

@VRamazing
Created September 23, 2019 13:45
Show Gist options
  • Save VRamazing/053c69d1a267268379e93133af4b837e to your computer and use it in GitHub Desktop.
Save VRamazing/053c69d1a267268379e93133af4b837e to your computer and use it in GitHub Desktop.
DFS, BFS algorithm
function Graph(v){
this.vertices = v;
this.edges = 0;
this.adj = []
for(var i=0; i<this.vertices; ++i){
this.adj[i]=[];
// this.adj[i].push("");
}
this.addEdge = addEdge;
this.showGraph = showGraph;
this.dfs = dfs;
this.bfs = bfs;
this.initMarkedList = initMarkedList
this.marked = [];
}
function initMarkedList(){
for(var i=0; i<this.vertices; ++i){
this.marked[i] = false;
}
console.log(this.marked);
}
function addEdge(v,w){
this.adj[v].push(w);
this.adj[w].push(v);
this.edges++;
}
function showGraph(){
var currentStr = ""
for(var i =0; i<this.vertices; ++i){
currentStr = i+ "->";
for(var j=0; j<this.vertices; ++j){
if(this.adj[i][j]!=undefined){
currentStr += this.adj[i][j] + ' ';
}
}
console.log(currentStr)
}
}
function dfs(v){
this.marked[v] = true;
if(this.adj[v]!=undefined){
console.log("Visited vertex: " + v);
this.adj[v].forEach(function(w){
if(!this.marked[w]){
this.dfs(w);
}
}, this)
}
}
function bfs(s){
this.marked[s] = true;
var queue = [];
queue.push(s);
while(queue.length > 0){
var v = queue.shift();
if(v!==undefined){
console.log('Visited vertex:' + v);
}
this.adj[v].forEach(function(w){
if(!this.marked[w]){
this.marked[w]=true;
queue.push(w);
}
}, this)
}
}
g = new Graph(6);
g.initMarkedList();
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,3);
g.addEdge(2,4);
g.addEdge(0,5);
g.showGraph();
console.log("------d-f-s------");
g.dfs(0);
g.initMarkedList();
console.log("------b-f-s------");
g.bfs(0);
g.initMarkedList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment