-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph[DepthFirstSearchAndBreathFirstSearch].js
More file actions
65 lines (61 loc) · 1.65 KB
/
Graph[DepthFirstSearchAndBreathFirstSearch].js
File metadata and controls
65 lines (61 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//Graph Constructor Class
/*@param v = vertices
*/
function Graph(v){
this.marked = [];
this.edgeTo = [];
this.edges = 0;
this.vertices = v;
this.adj = [];
for(var i = 0; i < this.vertices; i++){
this.adj[i] = [];
}
for(var j = 0; j < this.vertices; j++){
this.marked[j] = false;
}
}
Graph.prototype.addEdge = function(v,w){
this.adj[v].push(w);
this.adj[w].push(v);
this.edges++;
}
Graph.prototype.show = function(){
for (var i = 0; i < this.vertices; i++){
console.log(i+ "--->");
for (var j = 0; j < this.vertices; j++){
if (this.adj[i][j] != undefined){
console.log(this.adj[i][j]);
}
}
}
}
Graph.prototype.depthFirstSearch = function(v){
this.marked[v] = true;
if(this.adj[v] != undefined){
console.log("Visited "+v);
for (var i = 0; i < this.adj[v].length; i++){
if(!this.marked[this.adj[v][i]]){
this.depthFirstSearch(this.adj[v][i]);
}
}
}
}
Graph.prototype.BreathFirstSearch = function(v){
var currentVertice = null;
var queue = [];
this.marked[v] = true;
queue.push(v);
while(queue.length > 0){
var w = queue.shift();
console.log("Marked "+w +" With Children");
for (var i = 0; i < this.adj[w].length; i++){
currentVertice = this.adj[w][i];
if(!this.marked[currentVertice]){
console.log(currentVertice);
this.edgeTo[currentVertice] = w;
this.marked[currentVertice] = true;
queue.push(currentVertice);
}
}
}
}