-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathunweighted_undirected.js
82 lines (76 loc) · 2.3 KB
/
unweighted_undirected.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
class Graph {
constructor() {
this.numberOfVertices = 0;
this.adjacentList = {};
}
addVertex(vertex) {
if (!this.adjacentList[vertex]) {
this.adjacentList[vertex] = [];
this.numberOfVertices++;
return true;
}
return false;
}
addEdge(firstVertex, secondVertex) {
if (this.adjacentList[firstVertex] && this.adjacentList[secondVertex]) {
this.adjacentList[firstVertex].push(secondVertex);
this.adjacentList[secondVertex].push(firstVertex);
return true;
}
return false;
}
removeEdge(firstVertex, secondVertex) {
if (this.adjacentList[firstVertex] && this.adjacentList[secondVertex]) {
this.adjacentList[firstVertex] = this.adjacentList[firstVertex].filter(
(v) => v - secondVertex
);
this.adjacentList[secondVertex] = this.adjacentList[secondVertex].filter(
(v) => v - firstVertex
);
return true;
}
return false;
}
removeVertex(vertex) {
if (!this.adjacentList[vertex]) return undefined;
while (this.adjacentList[vertex].length) {
let temp = this.adjacentList[vertex].pop();
this.removeEdge(vertex, temp);
}
delete this.adjacentList[vertex];
this.numberOfVertices--;
return this;
}
showConnections() {
const allVertices = Object.keys(this.adjacentList);
for (let vertex of allVertices) {
const vertexConnections = this.adjacentList[vertex];
let connections = "";
for (let vertex of vertexConnections) {
connections += vertex + " ";
}
console.log(vertex + " --> ", connections);
}
}
}
const myGraph = new Graph();
console.log(myGraph.addVertex("1"));
console.log(myGraph.addVertex("2"));
console.log(myGraph.addVertex("3"));
console.log(myGraph.addVertex("4"));
console.log(myGraph.addVertex("5"));
console.log(myGraph.addVertex("6"));
console.log(myGraph);
console.log(myGraph.addEdge("1", "2"));
console.log(myGraph.addEdge("1", "3"));
console.log(myGraph.addEdge("2", "3"));
console.log(myGraph.addEdge("2", "4"));
console.log(myGraph.addEdge("3", "5"));
console.log(myGraph);
console.log(myGraph.removeEdge("3", "5"));
console.log(myGraph.removeEdge("2", "4"));
console.log(myGraph);
console.log(myGraph.removeVertex("5"));
console.log(myGraph.removeVertex("4"));
console.log(myGraph);
myGraph.showConnections();