-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathprimsAlgorithmMST.java
More file actions
83 lines (68 loc) · 2.27 KB
/
primsAlgorithmMST.java
File metadata and controls
83 lines (68 loc) · 2.27 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.*;
import java.lang.*;
import java.io.*;
class MinSpanTree {
// Vertices in Graph
private static final int V = 5;
// Finds Vertex with Min Key
int minKey(int key[], Boolean mstSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}
// To print MST Stored
void printMST(int parent[], int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
}
// To print MST through matrix representation
void prim_MST(int graph[][])
{
// Array to store constructed MST
int parent[] = new int[V];
// Key values used to pick minimum weight edge in cut
int key[] = new int[V];
// To represent set of vertices included in MST
Boolean mstSet[] = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
printMST(parent, graph);
}
public static void main(String[] args) {
MinSpanTree t = new MinSpanTree();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of vertices in the graph: ");
int V = sc.nextInt();
int[][] graph = new int[V][V];
System.out.println("Enter the adjacency matrix (space separated, row by row):");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
graph[i][j] = sc.nextInt();
}
}
t.prim_MST(graph);
sc.close();
}
}