-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGraph.js
73 lines (66 loc) · 1.72 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
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
if (this.adjacencyList[v1] && this.adjacencyList[v2]) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
}
removeEdge(v1, v2) {
if (this.adjacencyList[v1] && this.adjacencyList[v2]) {
this.adjacencyList[v1] = this.adjacencyList[v1].filter(v => v !== v2);
this.adjacencyList[v2] = this.adjacencyList[v2].filter(v => v !== v1);
}
}
removeVertex(vertex) {
if (this.adjacencyList[vertex]) {
for (let v of this.adjacencyList[vertex]) this.removeEdge(v, vertex);
delete this.adjacencyList[vertex];
}
}
DFSRecursive(start) {
const visited = new Set();
const helper = vertex => {
if (!visited.has(vertex)) {
visited.add(vertex);
let children = this.adjacencyList[vertex];
for (let child of children) helper(child);
}
};
helper(start);
return Array.from(visited);
}
DFSIterative(start) {
if (!this.adjacencyList[start]) return [];
const stack = [start];
const visited = new Set();
while (stack.length) {
let current = stack.pop();
visited.add(current);
let children = this.adjacencyList[current];
for (let child of children) {
if (!visited.has(child)) stack.push(child);
}
}
return Array.from(visited);
}
BFS(start) {
if (!this.adjacencyList[start]) return [];
const queue = [start];
const visited = new Set();
while (queue.length) {
let current = queue.shift();
visited.add(current);
let children = this.adjacencyList[current];
for (let child of children) {
if (!visited.has(child)) queue.push(child);
}
}
return Array.from(visited);
}
}