forked from pandeyprem/DSA-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimsAlgo.java
More file actions
99 lines (94 loc) · 2.94 KB
/
PrimsAlgo.java
File metadata and controls
99 lines (94 loc) · 2.94 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.LinkedList;
import java.util.TreeSet;
import java.util.Comparator;
public class PrimsAlgo {
class newnode {
int destination;
int weight;
newnode(int a, int b)
{
destination = a;
weight = b;
}
}
static class Graph {
int V;
LinkedList<newnode>[] adj;
Graph(int edge)
{
V = edge;
adj = new LinkedList[V];
for (int o = 0; o < V; o++)
adj[o] = new LinkedList<>();
}
}
class node {
int vertex;
int key;
}
class comparator implements Comparator<node> {
@Override
public int compare(node originnode, node newnode)
{
return originnode.key - newnode.key;
}
}
void addEdge(Graph graph, int src, int destination, int weight)
{
newnode originnode = new newnode(destination, weight);
newnode node = new newnode(src, weight);
graph.adj[src].addLast(originnode);
graph.adj[destination].addLast(node);
}
void prims_mst(Graph graph)
{
Boolean[] mstset = new Boolean[graph.V];
node[] edge = new node[graph.V];
int[] parent = new int[graph.V];
for (int o = 0; o < graph.V; o++)
edge[o] = new node();
for (int o = 0; o < graph.V; o++) {
mstset[o] = false;
edge[o].key = Integer.MAX_VALUE;
edge[o].vertex = o;
parent[o] = -1;
}
mstset[0] = true;
edge[0].key = 0;
TreeSet<node> queue = new TreeSet<node>(new comparator());
for (int o = 0; o < graph.V; o++)
queue.add(edge[o]);
while (!queue.isEmpty()) {
node originnode = queue.pollFirst();
mstset[originnode.vertex] = true;
for (newnode iterator : graph.adj[originnode.vertex]) {
if (mstset[iterator.destination] == false) {
if (edge[iterator.destination].key > iterator.weight) {
queue.remove(edge[iterator.destination]);
edge[iterator.destination].key = iterator.weight;
queue.add(edge[iterator.destination]);
parent[iterator.destination] = originnode.vertex;
}
}
}
}
for (int o = 1; o < graph.V; o++)
System.out.println(parent[o] + " "+ "-" + " " + o);
}
public static void main(String[] args)
{
int V = 8;
Graph graph = new Graph(V);
prims g = new prims();
g.addEdge(graph, 0, 1, 10);
g.addEdge(graph, 1, 2, 12);
g.addEdge(graph, 1, 7, 14);
g.addEdge(graph, 1, 5, 6);
g.addEdge(graph, 2, 3, 7);
g.addEdge(graph, 3, 4, 9);
g.addEdge(graph, 4, 5, 11);
g.addEdge(graph, 5, 6, 12);
g.addEdge(graph, 6, 7, 13);
g.prims_mst(graph);
}
}