Skip to content

Commit 3d31b07

Browse files
authored
Create Graph.js
1 parent 5922942 commit 3d31b07

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

03-DataStructures/Graph.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Graph {
2+
constructor() {
3+
this.adjacencyList = new Map();
4+
}
5+
6+
// Add a vertex to the graph
7+
addVertex(vertex) {
8+
if (!this.adjacencyList.has(vertex)) {
9+
this.adjacencyList.set(vertex, []);
10+
}
11+
}
12+
13+
// Add an edge between two vertices
14+
addEdge(vertex1, vertex2) {
15+
this.adjacencyList.get(vertex1).push(vertex2);
16+
this.adjacencyList.get(vertex2).push(vertex1);
17+
}
18+
19+
// Remove an edge between two vertices
20+
removeEdge(vertex1, vertex2) {
21+
this.adjacencyList.set(
22+
vertex1,
23+
this.adjacencyList.get(vertex1).filter((vertex) => vertex !== vertex2)
24+
);
25+
this.adjacencyList.set(
26+
vertex2,
27+
this.adjacencyList.get(vertex2).filter((vertex) => vertex !== vertex1)
28+
);
29+
}
30+
31+
// Remove a vertex and its edges from the graph
32+
removeVertex(vertex) {
33+
const edges = this.adjacencyList.get(vertex);
34+
for (const edge of edges) {
35+
this.removeEdge(vertex, edge);
36+
}
37+
this.adjacencyList.delete(vertex);
38+
}
39+
40+
// Other graph operations (traversal, search, etc.) can be added here
41+
}
42+
43+
// Example usage:
44+
const graph = new Graph();
45+
46+
graph.addVertex('A');
47+
graph.addVertex('B');
48+
graph.addVertex('C');
49+
graph.addVertex('D');
50+
51+
graph.addEdge('A', 'B');
52+
graph.addEdge('A', 'C');
53+
graph.addEdge('B', 'D');
54+
graph.addEdge('C', 'D');
55+

0 commit comments

Comments
 (0)