-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.js
94 lines (53 loc) · 1.43 KB
/
Graph.js
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
// ======================================GRAPH======================================
class Graph {
constructor() {
this.vertices = [];
this.edges = {};
}
addVertex(vertex) {
this.vertices.push(vertex);
this.edges[vertex] = [];
}
addEdge(vertex1, vertex2) {
this.edges[vertex1].push(vertex2);
this.edges[vertex2].push(vertex1);
}
bfs(startVertex) {
const visited = {};
const queue = [];
visited[startVertex] = true;
queue.push(startVertex);
while (queue.length > 0) {
const vertex = queue.shift();
console.log(vertex);
this.edges[vertex].forEach( (neighbor) => {if (!visited[neighbor]) {visited[neighbor] = true; queue.push(neighbor);}} );
}
}
dfs(startVertex) {
const visited = {};
const dfsHelper = (vertex) => {
visited[vertex] = true;
console.log(vertex);
this.edges[vertex].forEach((neighbor) => { if (!visited[neighbor]) { dfsHelper(neighbor); } } );
};
dfsHelper(startVertex);
}
}
// ==========================TEST CASES==========================
const graph = new Graph();
// add vertices
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
// add edges
graph.addEdge("A", "B");
graph.addEdge("B", "C");
graph.addEdge("C", "D");
graph.addEdge("D", "A");
// perform BFS
console.log("BFS:");
graph.bfs("A");
// perform DFS
console.log("DFS:");
graph.dfs("A");