-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.html
69 lines (61 loc) · 2.14 KB
/
Graph.html
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
<!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>
<script>
class Graph{
constructor(){
this.adjacencyList = {};
}
addVertex(vertex){
if(!this.adjacencyList[vertex]){
this.adjacencyList[vertex] = [];
}
}
addEdge(vertex1, vertex2){
if(this.adjacencyList[vertex1] && this.adjacencyList[vertex2]){
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
}
removeEdge(vertex1, vertex2){
if(this.adjacencyList[vertex1] && this.adjacencyList[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();
}
delete this.adjacencyList[vertex];
}
printGraph(){
for(let vertex in this.adjacencyList){
console.log(vertex + " ->" + this.adjacencyList[vertex].join(", "))
}
}
}
let graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addEdge("A","B");
graph.addEdge("A","C");
graph.addEdge("B","D");
console.log("Graph after adding vertices and edges")
graph.printGraph();
graph.removeEdge("A", "B")
console.log("Graph After removing edge between A and B")
graph.printGraph();
graph.removeVertex("C");
console.log("Graph After Removing vertex C")
graph.printGraph();
</script>
</body>
</html>