Skip to content

Commit a8cac0d

Browse files
committed
Add Prims Algorithm using Greedy Technique to find Minimum Cost Spanning Trees
1 parent 03bb8ee commit a8cac0d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Prims.java

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.*;
2+
public class Prims {
3+
public static void main(String[] args) {
4+
int cost[][] = new int[10][10];
5+
int i, j, mincost = 0;
6+
Scanner sc = new Scanner(System.in);
7+
System.out.println("Enter the number of vertices: ");
8+
int n = sc.nextInt();
9+
System.out.println("Enter the cost matrix: ");
10+
for (i = 1; i <= n; i++) {
11+
for (j = 1; j <= n; j++) {
12+
cost[i][j] = sc.nextInt();
13+
}
14+
}
15+
System.out.println("Min Tree edges are");
16+
mincost = pr(cost, n, mincost);
17+
System.out.println("Minimum cost: " + mincost);
18+
}
19+
static int pr(int[][] cost, int n, int mincost) {
20+
int nearV[] = new int[10], t[][] = new int[10][10], u =0, i, j, k;
21+
for (i = 2; i <= n; i++)
22+
nearV[i] = 1;
23+
nearV[1] = 0;
24+
for (i = 1; i < n; i++) {
25+
int min = 999;
26+
for (j = 1; j <= n; j++) {
27+
if (nearV[j] != 0 && cost[j][nearV[j]] < min) {
28+
min = cost[j][nearV[j]];
29+
u = j;
30+
}
31+
}
32+
t[i][1] = u;
33+
t[i][2] = nearV[u];
34+
mincost += min;
35+
nearV[u] = 0;
36+
for (k = 1; k <= n; k++) {
37+
if (nearV[k] != 0 && cost[u][k] < cost[k]
38+
[nearV[k]])
39+
nearV[k] = u;
40+
}
41+
System.out.println(i + ": Minimum edge is <" + t[i]
42+
[2] + ", " + t[i][1] + ">\tCost: " + min);
43+
}
44+
return mincost;
45+
}
46+
}

0 commit comments

Comments
 (0)