-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.html
106 lines (83 loc) · 2.05 KB
/
graph.html
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<script type="text/javascript">
class Graph {
constructor () {
this.adjList = {}
}
addVertex (vertex) {
this.adjList[vertex] = [];
}
addEdge(fromVertex,toVertex) {
this.adjList[fromVertex].push(toVertex)
this.adjList[toVertex].push(fromVertex)
}
bfs(startNode,endNode) {
var visitedNodes = {}
Object.keys(this.adjList).forEach(function (vertex){
visitedNodes[vertex] = false;
})
var q = []
q.push(startNode)
visitedNodes[startNode] = true
while(q.length) {
var node = q.shift()
if (node==endNode) {
console.log("found:",node)
break
}
var neighborNodes = this.adjList[node]
console.log(node,q,neighborNodes,visitedNodes)
for (var i = 0; i < neighborNodes.length; i++) {
var newNode = neighborNodes[i]
if(!visitedNodes[newNode]) {
visitedNodes[newNode] = true;
q.push(newNode)
}
}
}
}
dfs(startNode,endNode) {
var visitedNodes = {}
Object.keys(this.adjList).forEach(function (vertex) {
visitedNodes[vertex] = false
})
var stack = []
stack.push(startNode)
visitedNodes[startNode] = true
while(stack.length){
var node = stack.pop()
visitedNodes[node] = true // needs improvement
console.log(node,stack,visitedNodes)
if (node == endNode) {
console.log("found:", node)
break;
}
var neighborNodes = this.adjList[node]
for (var i = 0; i < neighborNodes.length; i++) {
var newNode = neighborNodes[i]
if (!visitedNodes[newNode]){
stack.push(newNode)
}
}
}
}
}
// Using the above implemented graph class
var g = new Graph(6);
var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ];
// adding vertices
for (var i = 0; i < vertices.length; i++) {
g.addVertex(vertices[i]);
}
// adding edges
g.addEdge('A', 'B');
g.addEdge('A', 'D');
g.addEdge('A', 'E');
g.addEdge('B', 'C');
g.addEdge('D', 'E');
g.addEdge('E', 'F');
g.addEdge('E', 'C');
g.addEdge('C', 'F');
console.log(g.adjList)
//g.bfs('A','C')
g.dfs('A','B')
</script>