Skip to content

Commit a7a8e19

Browse files
authored
Merge pull request #206 from Mansi-Mittal/master
Prim's And kruskal's Algorithms
2 parents 01e2555 + ab9f2b0 commit a7a8e19

File tree

2 files changed

+290
-0
lines changed

2 files changed

+290
-0
lines changed
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Java program for Kruskal's algorithm to find Minimum Spanning Tree
2+
// of a given connected, undirected and weighted graph
3+
import java.util.*;
4+
import java.lang.*;
5+
import java.io.*;
6+
7+
class Graph
8+
{
9+
// A class to represent a graph edge
10+
class Edge implements Comparable<Edge>
11+
{
12+
int src, dest, weight;
13+
14+
// Comparator function used for sorting edges based on
15+
// their weight
16+
public int compareTo(Edge compareEdge)
17+
{
18+
return this.weight-compareEdge.weight;
19+
}
20+
};
21+
22+
// A class to represent a subset for union-find
23+
class subset
24+
{
25+
int parent, rank;
26+
};
27+
28+
int V, E; // V-> no. of vertices & E->no.of edges
29+
Edge edge[]; // collection of all edges
30+
31+
// Creates a graph with V vertices and E edges
32+
Graph(int v, int e)
33+
{
34+
V = v;
35+
E = e;
36+
edge = new Edge[E];
37+
for (int i=0; i<e; ++i)
38+
edge[i] = new Edge();
39+
}
40+
41+
// A utility function to find set of an element i
42+
// (uses path compression technique)
43+
int find(subset subsets[], int i)
44+
{
45+
// find root and make root as parent of i (path compression)
46+
if (subsets[i].parent != i)
47+
subsets[i].parent = find(subsets, subsets[i].parent);
48+
49+
return subsets[i].parent;
50+
}
51+
52+
// A function that does union of two sets of x and y
53+
// (uses union by rank)
54+
void Union(subset subsets[], int x, int y)
55+
{
56+
int xroot = find(subsets, x);
57+
int yroot = find(subsets, y);
58+
59+
// Attach smaller rank tree under root of high rank tree
60+
// (Union by Rank)
61+
if (subsets[xroot].rank < subsets[yroot].rank)
62+
subsets[xroot].parent = yroot;
63+
else if (subsets[xroot].rank > subsets[yroot].rank)
64+
subsets[yroot].parent = xroot;
65+
66+
// If ranks are same, then make one as root and increment
67+
// its rank by one
68+
else
69+
{
70+
subsets[yroot].parent = xroot;
71+
subsets[xroot].rank++;
72+
}
73+
}
74+
75+
// The main function to construct MST using Kruskal's algorithm
76+
void KruskalMST()
77+
{
78+
Edge result[] = new Edge[V]; // Tnis will store the resultant MST
79+
int e = 0; // An index variable, used for result[]
80+
int i = 0; // An index variable, used for sorted edges
81+
for (i=0; i<V; ++i)
82+
result[i] = new Edge();
83+
84+
// Step 1: Sort all the edges in non-decreasing order of their
85+
// weight. If we are not allowed to change the given graph, we
86+
// can create a copy of array of edges
87+
Arrays.sort(edge);
88+
89+
// Allocate memory for creating V ssubsets
90+
subset subsets[] = new subset[V];
91+
for(i=0; i<V; ++i)
92+
subsets[i]=new subset();
93+
94+
// Create V subsets with single elements
95+
for (int v = 0; v < V; ++v)
96+
{
97+
subsets[v].parent = v;
98+
subsets[v].rank = 0;
99+
}
100+
101+
i = 0; // Index used to pick next edge
102+
103+
// Number of edges to be taken is equal to V-1
104+
while (e < V - 1)
105+
{
106+
// Step 2: Pick the smallest edge. And increment the index
107+
// for next iteration
108+
Edge next_edge = new Edge();
109+
next_edge = edge[i++];
110+
111+
int x = find(subsets, next_edge.src);
112+
int y = find(subsets, next_edge.dest);
113+
114+
// If including this edge does't cause cycle, include it
115+
// in result and increment the index of result for next edge
116+
if (x != y)
117+
{
118+
result[e++] = next_edge;
119+
Union(subsets, x, y);
120+
}
121+
// Else discard the next_edge
122+
}
123+
124+
// print the contents of result[] to display the built MST
125+
System.out.println("Following are the edges in the constructed MST");
126+
for (i = 0; i < e; ++i)
127+
System.out.println(result[i].src+" -- "+result[i].dest+" == "+
128+
result[i].weight);
129+
}
130+
131+
// Driver Program
132+
public static void main (String[] args)
133+
{
134+
135+
/* Let us create following weighted graph
136+
10
137+
0--------1
138+
| \ |
139+
6| 5\ |15
140+
| \ |
141+
2--------3
142+
4 */
143+
int V = 4; // Number of vertices in graph
144+
int E = 5; // Number of edges in graph
145+
Graph graph = new Graph(V, E);
146+
147+
// add edge 0-1
148+
graph.edge[0].src = 0;
149+
graph.edge[0].dest = 1;
150+
graph.edge[0].weight = 10;
151+
152+
// add edge 0-2
153+
graph.edge[1].src = 0;
154+
graph.edge[1].dest = 2;
155+
graph.edge[1].weight = 6;
156+
157+
// add edge 0-3
158+
graph.edge[2].src = 0;
159+
graph.edge[2].dest = 3;
160+
graph.edge[2].weight = 5;
161+
162+
// add edge 1-3
163+
graph.edge[3].src = 1;
164+
graph.edge[3].dest = 3;
165+
graph.edge[3].weight = 15;
166+
167+
// add edge 2-3
168+
graph.edge[4].src = 2;
169+
graph.edge[4].dest = 3;
170+
graph.edge[4].weight = 4;
171+
172+
graph.KruskalMST();
173+
}
174+
}

data_structures/Graphs/prim.java

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
2+
//adjacency matrix representation of the graph
3+
4+
import java.util.*;
5+
import java.lang.*;
6+
import java.io.*;
7+
8+
class MST
9+
{
10+
// Number of vertices in the graph
11+
private static final int V=5;
12+
13+
// A utility function to find the vertex with minimum key
14+
// value, from the set of vertices not yet included in MST
15+
int minKey(int key[], Boolean mstSet[])
16+
{
17+
// Initialize min value
18+
int min = Integer.MAX_VALUE, min_index=-1;
19+
20+
for (int v = 0; v < V; v++)
21+
if (mstSet[v] == false && key[v] < min)
22+
{
23+
min = key[v];
24+
min_index = v;
25+
}
26+
27+
return min_index;
28+
}
29+
30+
// A utility function to print the constructed MST stored in
31+
// parent[]
32+
void printMST(int parent[], int n, int graph[][])
33+
{
34+
System.out.println("Edge Weight");
35+
for (int i = 1; i < V; i++)
36+
System.out.println(parent[i]+" - "+ i+" "+
37+
graph[i][parent[i]]);
38+
}
39+
40+
// Function to construct and print MST for a graph represented
41+
// using adjacency matrix representation
42+
void primMST(int graph[][])
43+
{
44+
// Array to store constructed MST
45+
int parent[] = new int[V];
46+
47+
// Key values used to pick minimum weight edge in cut
48+
int key[] = new int [V];
49+
50+
// To represent set of vertices not yet included in MST
51+
Boolean mstSet[] = new Boolean[V];
52+
53+
// Initialize all keys as INFINITE
54+
for (int i = 0; i < V; i++)
55+
{
56+
key[i] = Integer.MAX_VALUE;
57+
mstSet[i] = false;
58+
}
59+
60+
// Always include first 1st vertex in MST.
61+
key[0] = 0; // Make key 0 so that this vertex is
62+
// picked as first vertex
63+
parent[0] = -1; // First node is always root of MST
64+
65+
// The MST will have V vertices
66+
for (int count = 0; count < V-1; count++)
67+
{
68+
// Pick thd minimum key vertex from the set of vertices
69+
// not yet included in MST
70+
int u = minKey(key, mstSet);
71+
72+
// Add the picked vertex to the MST Set
73+
mstSet[u] = true;
74+
75+
// Update key value and parent index of the adjacent
76+
// vertices of the picked vertex. Consider only those
77+
// vertices which are not yet included in MST
78+
for (int v = 0; v < V; v++)
79+
80+
// graph[u][v] is non zero only for adjacent vertices of m
81+
// mstSet[v] is false for vertices not yet included in MST
82+
// Update the key only if graph[u][v] is smaller than key[v]
83+
if (graph[u][v]!=0 && mstSet[v] == false &&
84+
graph[u][v] < key[v])
85+
{
86+
parent[v] = u;
87+
key[v] = graph[u][v];
88+
}
89+
}
90+
91+
// print the constructed MST
92+
printMST(parent, V, graph);
93+
}
94+
95+
public static void main (String[] args)
96+
{
97+
/* Let us create the following graph
98+
2 3
99+
(0)--(1)--(2)
100+
| / \ |
101+
6| 8/ \5 |7
102+
| / \ |
103+
(3)-------(4)
104+
9 */
105+
MST t = new MST();
106+
int graph[][] = new int[][] {{0, 2, 0, 6, 0},
107+
{2, 0, 3, 8, 5},
108+
{0, 3, 0, 0, 7},
109+
{6, 8, 0, 0, 9},
110+
{0, 5, 7, 9, 0},
111+
};
112+
113+
// Print the solution
114+
t.primMST(graph);
115+
}
116+
}

0 commit comments

Comments
 (0)