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

Class GraphWeightedUndirectedAdjacencyList

Graphs/KruskalMST.js:48–106  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

46}
47
48class GraphWeightedUndirectedAdjacencyList {
49 // Weighted Undirected Graph class
50 constructor() {
51 this.connections = {}
52 this.nodes = 0
53 }
54
55 addNode(node) {
56 // Function to add a node to the graph (connection represented by set)
57 this.connections[node] = {}
58 this.nodes += 1
59 }
60
61 addEdge(node1, node2, weight) {
62 // Function to add an edge (adds the node too if they are not present in the graph)
63 if (!(node1 in this.connections)) {
64 this.addNode(node1)
65 }
66 if (!(node2 in this.connections)) {
67 this.addNode(node2)
68 }
69 this.connections[node1][node2] = weight
70 this.connections[node2][node1] = weight
71 }
72
73 KruskalMST() {
74 // Kruskal's Algorithm to generate a Minimum Spanning Tree (MST) of a graph
75 // Details: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm
76 // getting the edges in ascending order of weights
77 const edges = []
78 const seen = new Set()
79 for (const start of Object.keys(this.connections)) {
80 for (const end of Object.keys(this.connections[start])) {
81 if (!seen.has(`${start} ${end}`)) {
82 seen.add(`${end} ${start}`)
83 edges.push([start, end, this.connections[start][end]])
84 }
85 }
86 }
87 edges.sort((a, b) => a[2] - b[2])
88 // creating the disjoint set
89 const disjointSet = new DisjointSetTree()
90 Object.keys(this.connections).forEach((node) => disjointSet.makeSet(node))
91 // MST generation
92 const graph = new GraphWeightedUndirectedAdjacencyList()
93 let numEdges = 0
94 let index = 0
95 while (numEdges < this.nodes - 1) {
96 const [u, v, w] = edges[index]
97 index += 1
98 if (disjointSet.findSet(u) !== disjointSet.findSet(v)) {
99 numEdges += 1
100 graph.addEdge(u, v, w)
101 disjointSet.union(u, v)
102 }
103 }
104 return graph
105 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected