-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathgraph.js
69 lines (62 loc) · 1.41 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
class Graph {
constructor() {
this.adjacentList = {};
}
addVertex(vertex) {
if (!this.adjacentList[vertex]) this.adjacentList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacentList[v1].push(v2);
this.adjacentList[v2].push(v1);
}
// remove edge
removerEdge(v1, v2) {
this.adjacentList[v1] = this.adjacentList[v1].filter(v => {
return v !== v2;
});
this.adjacentList[v2] = this.adjacentList[v2].filter(v => {
return v !== v1;
});
}
// remove vertex
removeVertex(v1) {
while (this.adjacentList[v1].length) {
const v = this.adjacentList[v1].pop();
this.removerEdge(v, v1);
}
delete this.adjacentList[v1];
}
// dfs recurssion
dfsRecursion(start) {
let result = [];
let visited = {};
const adjacentList = this.adjacentList;
(function dfs(vertex) {
if (!vertex) return null;
visited[vertex] = true;
result.push(vertex);
adjacentList[vertex].forEach(n => {
if (!visited[n]) {
dfs(n);
}
});
})(start);
return result;
}
}
const g1 = new Graph();
g1.addVertex('A');
g1.addVertex('B');
g1.addVertex('C');
g1.addVertex('D');
g1.addVertex('E');
g1.addVertex('F');
g1.addEdge('A', 'B');
g1.addEdge('A', 'C');
g1.addEdge('B', 'D');
g1.addEdge('C', 'E');
g1.addEdge('D', 'E');
g1.addEdge('D', 'F');
g1.addEdge('E', 'F');
g1.dfsRecursion('A');
console.log(g1.dfsRecursion('A'));