PRIM
PRIM
Prim’s algorithm finds the cost of a minimum spanning tree from a weighted undirected
graph.
Prim’s algorithm begins by randomly selecting a vertex and adding the least expensive
edge from this vertex to the spanning tree. The algorithm continues to add the least
expensive edge from the vertices already added to the spanning tree to make it grow and
terminates when all the vertices are added to the spanning tree.
The algorithm is greedy in nature as it selects the least expensive edge from the vertices
already added to the spanning tree.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
class NodeCost {
int node; // Adjacent node
int cost; // Costance/cost to adjacent node
class Prims {
// Priority queue stores the object node-cost into the queue with
// the smallest cost node at the top.
PriorityQueue<NodeCost> pq = new
PriorityQueue<>(NodeCostComparator);
int mst_cost = 0;
while (!pq.isEmpty()) {
// Node 0
Collections.addAll(graph_1.get(0),
new NodeCost(1, 4),
new NodeCost(2, 1),
new NodeCost(3, 5));
// Node 1
Collections.addAll(graph_1.get(1),
new NodeCost(0, 4),
new NodeCost(3, 2),
new NodeCost(4, 3),
new NodeCost(5, 3));
// Node 2
Collections.addAll(graph_1.get(2),
new NodeCost(0, 1),
new NodeCost(3, 2),
new NodeCost(4, 8));
// Node 3
Collections.addAll(graph_1.get(3),
new NodeCost(0, 5),
new NodeCost(1, 2),
new NodeCost(2, 2),
new NodeCost(4, 1));
// Node 4
Collections.addAll(graph_1.get(4),
new NodeCost(1, 3),
new NodeCost(2, 8),
new NodeCost(3, 1),
new NodeCost(5, 4));
// Node 5
// Node 0
Collections.addAll(graph_2.get(0),
new NodeCost(1, 1),
new NodeCost(2, 2),
new NodeCost(3, 1),
new NodeCost(4, 1),
new NodeCost(5, 2),
new NodeCost(6, 1));
// Node 1
Collections.addAll(graph_2.get(1),
new NodeCost(0, 1),
new NodeCost(2, 2),
new NodeCost(6, 2));
// Node 2
Collections.addAll(graph_2.get(2),
new NodeCost(0, 2),
new NodeCost(1, 2),
new NodeCost(3, 1));
// Node 3
Collections.addAll(graph_2.get(3),
new NodeCost(0, 1),
new NodeCost(2, 1),
new NodeCost(4, 2));
// Node 4
Collections.addAll(graph_2.get(4),
new NodeCost(0, 1),
new NodeCost(3, 2),
new NodeCost(5, 2));
// Node 5
Collections.addAll(graph_2.get(5),
new NodeCost(0, 2),
new NodeCost(4, 2),
new NodeCost(6, 1));
// Node 6
Collections.addAll(graph_2.get(6),
new NodeCost(0, 1),
new NodeCost(1, 2),
new NodeCost(5, 1));
Output