-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAdjacencyList.js
128 lines (117 loc) · 3.18 KB
/
AdjacencyList.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
export class Graph {
constructor(directed = false) {
this.adjacencyList = {};
this.directed = directed;
}
addVertex(vertex) {
if(this.adjacencyList[vertex]) {
return 'Already Exists';
}
this.adjacencyList[vertex] = [];
return this.adjacencyList;
}
addEdge(vertex1, vertex2) {
if(!this.adjacencyList[vertex1]) {
return `${vertex1} not exists`;
}
if(!this.adjacencyList[vertex2]) {
return `${vertex2} not exists`;
}
this.adjacencyList[vertex1].push(vertex2);
if(!this.directed) {
this.adjacencyList[vertex2].push(vertex1);
}
return this.adjacencyList;
}
removeEdge(vertex1, vertex2) {
if(!this.adjacencyList[vertex1] || !this.adjacencyList[vertex2]) {
return 'invalid vertex';
}
this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(v => v !== vertex2);
if(!this.directed) {
this.adjacencyList[vertex2] = this.adjacencyList[vertex1].filter(v => v !== vertex1);
}
return this.adjacencyList;
}
removeVertex(vertex) {
const edges = this.adjacencyList[vertex]
edges.forEach(e => {
this.removeEdge(vertex, e);
});
delete this.adjacencyList[vertex];
return this.adjacencyList;
}
dfsRecursive(vertex) {
const visited = {};
const result = [];
const adjacencyList = this.adjacencyList;
(function dfs(vertex) {
if(!vertex) {
return null;
}
visited[vertex] = true;
result.push(vertex);
adjacencyList[vertex].forEach(neighbour => {
if(!visited[neighbour]) {
return dfs(neighbour);
}
})
})(vertex);
return result;
}
dfsIterative(vertex) {
if(!vertex) {
return null;
}
const stack = [vertex];
const visited = {};
const result = [];
while(stack.length) {
const current = stack.pop();
if(!visited[current]) {
visited[current] = true;
result.push(current);
stack.push(...this.adjacencyList[current]);
}
}
return result;
}
bfs(vertex) {
if(!vertex) {
return null;
}
const queue = [vertex];
const visited = {};
const result = [];
while(queue.length) {
const current = queue.shift();
if(!visited[current]) {
visited[current] = true;
result.push(current);
queue.push(...this.adjacencyList[current]);
}
}
return result;
}
}
const 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")
// A
// / \
// B C
// | |
// D --- E
// \ /
// F