-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_DSA.html
More file actions
77 lines (66 loc) · 1.73 KB
/
Copy pathgraph_DSA.html
File metadata and controls
77 lines (66 loc) · 1.73 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Graph DSA</h1>
<script>
class Graph {
constructor() {
this.data = {};
}
addVertex(vertex) {
if (!this.data[vertex]) {
this.data[vertex] = [];
}
}
addEdge(v1, v2) {
if (!this.data[v1]) {
this.addVertex(v1);
}
if (!this.data[v2]) {
this.addVertex(v2);
}
this.data[v1].push(v2);
this.data[v2].push(v1);
}
removeEdge(v1, v2) {
// console.warn("remove",this.data[v1])
this.data[v1] = this.data[v1].filter((item) => {
return item != v2;
});
this.data[v2] = this.data[v2].filter((item) => {
return item != v1;
});
}
removeVertex(vertex) {
if (!this.data[vertex]) {
return;
}
for (let item of this.data[vertex]) {
this.removeEdge(vertex, item);
}
delete this.data[vertex];
}
}
const graph1 = new Graph();
graph1.addVertex("A");
graph1.addVertex("B");
graph1.addVertex("C");
graph1.addVertex("D");
// console.warn(graph1.data);
graph1.addEdge("A", "B");
graph1.addEdge("A", "C");
graph1.addEdge("B", "C");
graph1.addEdge("B", "D");
// graph1.removeEdge("A","B");
// graph1.removeEdge("B","D");
// graph1.removeVertex('A')
graph1.removeVertex("D");
console.warn(graph1.data);
</script>
</body>
</html>