-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcourse-graph.js
104 lines (93 loc) · 2.49 KB
/
course-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
95
96
97
98
99
100
101
102
103
104
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
removeEdge(vertex1, vertex2) {
this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(
(v) => v !== vertex2
);
this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(
(v) => v !== vertex1
);
}
removeVertex(vertex) {
while (this.adjacencyList[vertex].length) {
const adjacentVertex = this.adjacencyList[vertex].pop();
this.removeEdge(vertex, adjacentVertex);
}
delete this.adjacencyList[vertex];
}
DFR(startVertex = "A") {
const arr = [];
const visited = {};
const self = this;
function walk(vertex) {
visited[vertex] = true;
arr.push(vertex);
for (let i = 0; i < self.adjacencyList[vertex].length; i++) {
if (visited[self.adjacencyList[vertex][i]]) continue;
walk(self.adjacencyList[vertex][i]);
}
}
walk(startVertex);
return arr;
}
DFL(startVertex = "A") {
const arr = [];
const visited = {};
let currentVertexes = [startVertex];
visited[startVertex] = true;
while (currentVertexes.length) {
const vertex = currentVertexes.pop();
arr.push(vertex);
for (let i = 0; i < this.adjacencyList[vertex].length; i++) {
if (!visited[this.adjacencyList[vertex][i]]) {
visited[this.adjacencyList[vertex][i]] = true;
currentVertexes.push(this.adjacencyList[vertex][i]);
}
}
}
return arr;
}
BFS(startVertex = "A") {
const arr = [];
const visited = {};
let currentVertexes = [startVertex];
visited[startVertex] = true;
while (currentVertexes.length) {
const vertex = currentVertexes.shift();
arr.push(vertex);
for (let i = 0; i < this.adjacencyList[vertex].length; i++) {
if (!visited[this.adjacencyList[vertex][i]]) {
visited[this.adjacencyList[vertex][i]] = true;
currentVertexes.push(this.adjacencyList[vertex][i]);
}
}
}
return arr;
}
}
let g = new Graph();
g.addVertex("A");
g.addVertex("B");
g.addVertex("C");
g.addVertex("D");
g.addVertex("E");
g.addVertex("F");
g.addEdge("A", "B");
g.addEdge("A", "C");
g.addEdge("B", "D");
g.addEdge("C", "E");
g.addEdge("D", "E");
g.addEdge("D", "F");
g.addEdge("E", "F");
g.DFR();
g.DFL();
console.log("A");