-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathPrims_algo.java
More file actions
79 lines (73 loc) · 2.23 KB
/
Prims_algo.java
File metadata and controls
79 lines (73 loc) · 2.23 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
import java.util.*;
import java.lang.*;
import java.io.*;
class Prims_algo
{
private static final int V = 5;
int minKey(int key[], Boolean mstSet[])
{
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;
}
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]]);
}
void primMST(int graph[][])
{
int parent[] = new int[V];
int key[] = new int[V];
Boolean mstSet[] = new Boolean[V];
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)
{
System.out.print('\f');
Scanner sc = new Scanner(System.in);
Prims_algo tree = new Prims_algo();
System.out.println("Enter the number of vertices");
int vertices = sc.nextInt();
int x;
int graph[][] = new int[vertices][vertices];
for(int i=0;i<vertices;i++)
{
for(int j=0;j<vertices;j++)
{
System.out.println("Enter the weight of the egde between " + i +" " +j);
x = sc.nextInt();
graph[i][j] = x;
}
}
long start = System.nanoTime();
tree.primMST(graph);
long end = System.nanoTime();
long microseconds = (end - start) / 1000;
System.out.println("Time for MST using prim's algo in micro seconds is "+microseconds);
}
}