forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimMST.js
More file actions
Latest commit
65 lines (60 loc) · 2.03 KB
/
Copy pathPrimMST.js
File metadata and controls
65 lines (60 loc) · 2.03 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
56
57
58
59
60
61
62
63
64
65
import{KeyPriorityQueue}from'../Data-Structures/Heap/KeyPriorityQueue'
classGraphWeightedUndirectedAdjacencyList{
// Weighted Undirected Graph class
constructor(){
this.connections={}
}
addNode(node){
// Function to add a node to the graph (connection represented by set)
this.connections[node]={}
}
addEdge(node1,node2,weight){
// Function to add an edge (adds the node too if they are not present in the graph)
if(!(node1inthis.connections)){
this.addNode(node1)
}
if(!(node2inthis.connections)){
this.addNode(node2)
}
this.connections[node1][node2]=weight
this.connections[node2][node1]=weight
}
PrimMST(start){
// Prim's Algorithm to generate a Minimum Spanning Tree (MST) of a graph
// Details: https://en.wikipedia.org/wiki/Prim%27s_algorithm
constdistance={}
constparent={}
constpriorityQueue=newKeyPriorityQueue()
// Initialization
for(constnodeinthis.connections){
distance[node]=node===start.toString() ? 0 : Infinity
parent[node]=null
priorityQueue.push(node,distance[node])
}
// Updating 'distance' object
while(!priorityQueue.isEmpty()){
constnode=priorityQueue.pop()
Object.keys(this.connections[node]).forEach((neighbour)=>{
if(
priorityQueue.contains(neighbour)&&
distance[node]+this.connections[node][neighbour]<
distance[neighbour]
){
distance[neighbour]=
distance[node]+this.connections[node][neighbour]
parent[neighbour]=node
priorityQueue.update(neighbour,distance[neighbour])
}
})
}
// MST Generation from the 'parent' object
constgraph=newGraphWeightedUndirectedAdjacencyList()
Object.keys(parent).forEach((node)=>{
if(node&&parent[node]){
graph.addEdge(node,parent[node],this.connections[node][parent[node]])
}
})
returngraph
}
}
export{GraphWeightedUndirectedAdjacencyList}