-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.js
More file actions
55 lines (46 loc) · 1.36 KB
/
Graph.js
File metadata and controls
55 lines (46 loc) · 1.36 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
class Graph {
constructor() {
this.adjacencyList = new Map();
}
// Add a vertex to the graph
addVertex(vertex) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
// Add an edge between two vertices
addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1).push(vertex2);
this.adjacencyList.get(vertex2).push(vertex1);
}
// Remove an edge between two vertices
removeEdge(vertex1, vertex2) {
this.adjacencyList.set(
vertex1,
this.adjacencyList.get(vertex1).filter((vertex) => vertex !== vertex2)
);
this.adjacencyList.set(
vertex2,
this.adjacencyList.get(vertex2).filter((vertex) => vertex !== vertex1)
);
}
// Remove a vertex and its edges from the graph
removeVertex(vertex) {
const edges = this.adjacencyList.get(vertex);
for (const edge of edges) {
this.removeEdge(vertex, edge);
}
this.adjacencyList.delete(vertex);
}
// Other graph operations (traversal, search, etc.) can be added here
}
// Example usage:
const 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');
graph.addEdge('C', 'D');