GraphsLearning
Implementation of UnDirected and Weighted Graph
JavaScript Solution & Complexity Analysis
Run & test in browserJavaScript Lab Sandbox
class UndirectedWeightedGraph {
constructor() {
this.adjacencyList = new Map();
}
addVertex(vertex) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
addEdge(source, destination, weight) {
this.addVertex(source);
this.addVertex(destination);
const sourceEdges = this.adjacencyList.get(source);
if (!sourceEdges.find((edge) => edge.node === destination)) {
sourceEdges.push({ node: destination, weight: weight });
}
const destinationEdges = this.adjacencyList.get(destination);
if (!destinationEdges.find((edge) => edge.node === source)) {
destinationEdges.push({ node: source, weight: weight });
}
}
print() {
for (const [vertex, edges] in this.adjacencyList) {
const formattedEdges = edges
.map((edge) => `${edge.node} (weight: ${edge.weight})`)
.join(", ");
console.log(`${vertex} -> ${formattedEdges}`);
}
}
}
const graph = new UndirectedWeightedGraph();
graph.addEdge(1, 2, 10);
graph.addEdge(1, 3, 15);
graph.addEdge(2, 4, 5);
graph.addEdge(2, 5, 20);
graph.addEdge(3, 4, 25);
graph.addEdge(4, 5, 30);
graph.print();
Console Output
Click "Run Code" above to execute and view output...