Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d2d4960

Browse files
Merge pull request fnplus#356 from shanky199912/kruskal
added kruskal algo in java
2 parents 9eb6e45 + f0d822f commit d2d4960

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import java.util.*;
2+
3+
class GFG
4+
{
5+
6+
private static int V = 5;
7+
private static int[] parent = new int[V];
8+
private static int INF = Integer.MAX_VALUE;
9+
10+
// Find set of vertex i
11+
private static int find(int i)
12+
{
13+
while (parent[i] != i)
14+
i = parent[i];
15+
return i;
16+
}
17+
18+
private static void union1(int i, int j)
19+
{
20+
int a = find(i);
21+
int b = find(j);
22+
parent[a] = b;
23+
}
24+
25+
// Finds MST using Kruskal's algorithm
26+
private static void kruskalMST(int[][] cost)
27+
{
28+
int mincost = 0; // Cost of min MST.
29+
30+
// Initialize sets of disjoint sets.
31+
for (int i = 0; i < V; i++)
32+
parent[i] = i;
33+
34+
// Include minimum weight edges one by one
35+
int edge_count = 0;
36+
while (edge_count < V - 1)
37+
{
38+
int min = INF, a = -1, b = -1;
39+
for (int i = 0; i < V; i++)
40+
{
41+
for (int j = 0; j < V; j++)
42+
{
43+
if (find(i) != find(j) && cost[i][j] < min)
44+
{
45+
min = cost[i][j];
46+
a = i;
47+
b = j;
48+
}
49+
}
50+
}
51+
52+
union1(a, b);
53+
System.out.printf("Edge %d:(%d, %d) cost:%d \n",
54+
edge_count++, a, b, min);
55+
mincost += min;
56+
}
57+
System.out.printf("\n Minimum cost= %d \n", mincost);
58+
}
59+
60+
public static void main(String[] args)
61+
{
62+
int[][] cost = {
63+
{INF, 2, INF, 6, INF},
64+
{2, INF, 3, 8, 5},
65+
{INF, 3, INF, INF, 7},
66+
{6, 8, INF, INF, 9},
67+
{INF, 5, 7, 9, INF},
68+
};
69+
70+
kruskalMST(cost);
71+
}
72+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /