-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
72 lines (63 loc) · 1.61 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
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
}
}
removeVertex(vrtx) {
const linkedVertexes = this.adjacencyList[vrtx];
linkedVertexes.forEach((v) => {
this.removeEdge(vrtx, v);
});
delete this.adjacencyList[vrtx];
}
addEdge(v1, v2) {
this.adjacencyList[v1]?.push(v2);
this.adjacencyList[v2]?.push(v1);
}
removeEdge(v1, v2) {
this.adjacencyList[v1] = this.adjacencyList[v1].filter((v) => v !== v2);
this.adjacencyList[v2] = this.adjacencyList[v2].filter((v) => v !== v1);
}
DFSrecurcive(vertex) {
const result = [];
const visited = {};
const DFS = (v) => {
if (this.adjacencyList[v].length === 0) return;
visited[v] = true;
result.push(v);
for (const sibl of this.adjacencyList[v]) {
console.log(sibl);
if (!(sibl in visited)) DFS(sibl);
}
};
DFS(vertex);
return [result, visited];
}
BFS(v) {
const queue = [v];
const result = [];
const visited = { [v]: true };
while (queue.length) {
const removed = queue.shift();
result.push(removed);
for (const vert of this.adjacencyList[removed]) {
if (!(vert in visited)) {
visited[vert] = true;
queue.push(vert);
}
}
}
return result;
}
}
const g = new Graph();
// g.addVertex('Dallas');
// g.addVertex('Las Vegas');
// g.addVertex('Los Santos');
// g.addEdge('Dallas', 'Las Vegas');
// g.addEdge('Dallas', 'Los Santos');
// g.addEdge('Las Vegas', 'Los Santos');