Skip to content

Commit 6ebc400

Browse files
committed
Prim's algorithm for MST, Java implementation
1 parent 27ae9d3 commit 6ebc400

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

Graph/PrimsMST/PrimsMST.java

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import java.util.*;
2+
3+
/**
4+
* @author dbatchunag
5+
*/
6+
7+
public class PrimsMST {
8+
9+
class Node implements Comparable<Node> {
10+
final int index;
11+
int distance;
12+
int parent;
13+
Node(int index, int distance, int parent) {
14+
this.index = index;
15+
this.distance = distance;
16+
this.parent = parent;
17+
}
18+
19+
@Override
20+
public int compareTo(Node other) {
21+
return distance - other.distance;
22+
}
23+
};
24+
25+
// A utility function to print the constructed MST stored in parent[]
26+
void printMST(final int parent[], final int [][] graph) {
27+
final int V = graph.length;
28+
int minCost = 0;
29+
System.out.println("Edge Weight");
30+
for (int i = 0; i < V; i++) {
31+
if (parent[i]==-1) {
32+
//it's our root
33+
continue;
34+
}
35+
final int cost = graph[i][parent[i]];
36+
System.out.println(String.format("%d - %d %d", parent[i], i, cost));
37+
minCost += cost;
38+
}
39+
System.out.println(String.format("Total Cost: %d", minCost));
40+
}
41+
42+
void primMST(final int[][] graph) {
43+
final int V = graph.length;
44+
final int [] parent = new int[V]; // Backtrack array to construct MST back
45+
46+
// Keep track of vertices that already covered
47+
final boolean[] covered = new boolean[V];
48+
//Priority queue for getting closest uncovered vertex
49+
final PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
50+
51+
//We can start with any node as a root
52+
final int root = (int) (Math.random() * V);
53+
priorityQueue.add(new Node(root, 0, -1));
54+
55+
// We continue until we check all possibilities.
56+
while (!priorityQueue.isEmpty()) {
57+
// Pick the closest vertex from current sub-MST
58+
final Node node = priorityQueue.poll();
59+
final int u = node.index;
60+
if (!covered[u]) {
61+
covered[u] = true;
62+
parent[u] = node.parent;
63+
for (int v = 0; v < V; v++) {
64+
// This process could be faster if we use adjacency list.
65+
if (graph[u][v] > 0 && !covered[v]) {
66+
priorityQueue.add(new Node(v, graph[u][v], u));
67+
}
68+
}
69+
}
70+
}
71+
72+
// print the constructed MST
73+
printMST(parent, graph);
74+
}
75+
76+
77+
private void run() {
78+
/* Let us create the following graph
79+
2 3
80+
(0)--(1)--(2)
81+
| / \ |
82+
6| 8/ \5 |7
83+
| / \ |
84+
(3)-------(4)
85+
9 */
86+
final int [][] graph = new int[][] {
87+
{0, 2, 0, 6, 0},
88+
{2, 0, 3, 8, 5},
89+
{0, 3, 0, 0, 7},
90+
{6, 8, 0, 0, 9},
91+
{0, 5, 7, 9, 0},
92+
};
93+
94+
primMST(graph);
95+
System.out.println("\nAnswer should be 16");
96+
}
97+
98+
public static void main(String[] args) {
99+
new PrimsMST().run();
100+
}
101+
102+
}
103+

0 commit comments

Comments
 (0)