MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / GraphWeightedUndirectedAdjacencyList

Class GraphWeightedUndirectedAdjacencyList

Graphs/PrimMST.js:2–63  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import { KeyPriorityQueue } from '../Data-Structures/Heap/KeyPriorityQueue'
2class GraphWeightedUndirectedAdjacencyList {
3 // Weighted Undirected Graph class
4 constructor() {
5 this.connections = {}
6 }
7
8 addNode(node) {
9 // Function to add a node to the graph (connection represented by set)
10 this.connections[node] = {}
11 }
12
13 addEdge(node1, node2, weight) {
14 // Function to add an edge (adds the node too if they are not present in the graph)
15 if (!(node1 in this.connections)) {
16 this.addNode(node1)
17 }
18 if (!(node2 in this.connections)) {
19 this.addNode(node2)
20 }
21 this.connections[node1][node2] = weight
22 this.connections[node2][node1] = weight
23 }
24
25 PrimMST(start) {
26 // Prim's Algorithm to generate a Minimum Spanning Tree (MST) of a graph
27 // Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm
28 const distance = {}
29 const parent = {}
30 const priorityQueue = new KeyPriorityQueue()
31 // Initialization
32 for (const node in this.connections) {
33 distance[node] = node === start.toString() ? 0 : Infinity
34 parent[node] = null
35 priorityQueue.push(node, distance[node])
36 }
37 // Updating 'distance' object
38 while (!priorityQueue.isEmpty()) {
39 const node = priorityQueue.pop()
40 Object.keys(this.connections[node]).forEach((neighbour) => {
41 if (
42 priorityQueue.contains(neighbour) &&
43 distance[node] + this.connections[node][neighbour] <
44 distance[neighbour]
45 ) {
46 distance[neighbour] =
47 distance[node] + this.connections[node][neighbour]
48 parent[neighbour] = node
49 priorityQueue.update(neighbour, distance[neighbour])
50 }
51 })
52 }
53
54 // MST Generation from the 'parent' object
55 const graph = new GraphWeightedUndirectedAdjacencyList()
56 Object.keys(parent).forEach((node) => {
57 if (node && parent[node]) {
58 graph.addEdge(node, parent[node], this.connections[node][parent[node]])
59 }
60 })

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected