-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrim's Algorithm
56 lines (51 loc) · 1.31 KB
/
Prim's Algorithm
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
//Prim's Algorithm
//Java Code
import java.util.Scanner;
public class prims {
public static void main(String[] args) {
int n;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices");
n = sc.nextInt();
int cA[][] = new int[n][n];
int visited[] = new int[n];
int unvisited[] = new int[n];
System.out.println("Enter the cost adjacency matrix");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cA[i][j] = sc.nextInt();
System.out.println("Enter the source vertex");
int sV = sc.nextInt();
visited[sV - 1] = 1;
for (int i = 0; i < n; i++) {
if (i != sV - 1)
unvisited[i] = 1;
}
int index, minCost, source;
index = minCost = source = 0;
System.out.println("Edge set :");
for (int i = 1; i < n; i++) {
int min = 9999;
for (int j = 0; j < n; j++) {
if (visited[j] == 1) {
for (int k = 0; k < n; k++) {
if ((unvisited[k] == 1) && (cA[j][k] != 9999)) {
if (min > cA[j][k]) {
min = cA[j][k];
source = j;
index = k;
}
}
}
}
}
visited[index] = 1;
unvisited[index] = 0;
System.out.print("(" + (source + 1) + "," + (index + 1) + ")");
minCost += min;
}
System.out
.println("\nThe minimum cost of the spanning tree = " + minCost);
}
}