-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadjacencyList.js
81 lines (69 loc) · 1.74 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
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = new Set();
}
}
addEdge(vertex1, vertex2) {
if (!this.adjacencyList[vertex1]) {
this.addVertex(vertex1);
}
if (!this.adjacencyList[vertex2]) {
this.addVertex(vertex2);
}
this.adjacencyList[vertex1].add(vertex2);
this.adjacencyList[vertex2].add(vertex1);
}
hasEdge(vertex1, vertex2) {
return (
this.adjacencyList[vertex1].has(vertex2) &&
this.adjacencyList[vertex2].has(vertex1)
);
}
removeEdge(vertex1, vertex2) {
this.adjacencyList[vertex1].delete(vertex2);
this.adjacencyList[vertex2].delete(vertex1);
}
removeVertex(vertex) {
if (!this.adjacencyList[vertex]) {
return;
}
for (let adjacentVertex of this.adjacencyList[vertex]) {
this.removeEdge(vertex, adjacentVertex);
}
delete this.adjacencyList[vertex];
}
bfs(startVertex) {
const vistited = {};
const queue = [];
vistited[startVertex] = true;
queue.push(startVertex);
while (queue.length > 0) {
const currentVertex = queue.shift();
console.log(currentVertex);
this.adjacencyList[currentVertex].forEach((neighbor) => {
if (!vistited[neighbor]) {
vistited[neighbor] = true;
queue.push(neighbor);
}
});
}
}
display() {
for (let vertex in this.adjacencyList) {
console.log(vertex, "-->", [...this.adjacencyList[vertex]]);
}
}
}
const graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addEdge("A", "B");
graph.addEdge("B", "C");
graph.hasEdge("A", "B");
graph.bfs("A");
graph.display();