Beruflich Dokumente
Kultur Dokumente
Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a
connected weighted graph. It finds a subset of the edges that forms a tree that includes every
vertex, where the total weight of all the edges in the tree is minimized. This algorithm is directly
based on the MST (minimum spanning tree) property.
Example
A Simple Weighted GraphMinimum-Cost Spanning Tree
Kruskal's Algorithm
1. MST-KRUSKAL(G, w)
2.
3. 1. A ← Ø
4.
5. 2. for each vertex v V[G]
6. 3. do MAKE-SET(v)
7. 4. sort the edges of E into nondecreasing order by weight w
8. 5. for each edge (u, v) E, taken in nondecreasing order by weight
9. 6. do if FIND-SET(u) ≠ FIND-SET(v)
10. 7. then A ← A {(u, v)}
11. 8. UNION(u, v)
12. 9. return A
Example
Edge No. Vertex Pair Edge Weight
E1 (0,2) 1
E2 (3,5) 2
E3 (0,1) 3
E4 (1,4) 3
E5 (2,5) 4
E6 (1,2) 5
E7 (2,3) 5
E8 (0,3) 6
E9 (2,4) 6
E10 (4,5) 6
Add Edge E1
Add Edge E2
Add Edge E3
Add Edge E4
Add Edge E5
1. #include<stdio.h>
2. #include<conio.h>
3. #include<stdlib.h>
4. int i,j,k,a,b,u,v,n,ne=1;
5. int min,mincost=0,cost[9][9],parent[9];
6.
7. int find(int);
8. int uni(int,int);
9.
10. Int main()
11. {
12.
13. clrscr();
14.
15. printf("\n\tImplementation of Kruskal's algorithm\n");
16.
17. printf("\nEnter the no. of vertices:");
18. scanf("%d",&n)
19. ;
20. printf("\nEnter the cost adjacency matrix:\n");
21. for(i=1;i<=n;i++)
22.
23. {
24. for(j=1;j<=n;j++)
25.
26. {
27. scanf("%d",&cost[i][j]);
28.
29. if(cost[i][j]==0)
30. cost[i][j]=999;
31. }
32. }
33. printf("The edges of Minimum Cost Spanning Tree are\n");
34. while(ne < n)
35. {
36. for(i=1,min=999;i<=n;i++)
37. {
38. for(j=1;j <= n;j++)
39. {
40. if(cost[i][j] < min)
41. {
42. min=cost[i][j];
43. a=u=i;
44. b=v=j;
45. }
46. }
47. }
48. u=find(u);
49. v=find(v);
50. if(uni(u,v))
51. {
52. printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
53. mincost +=min;
54. }
55. cost[a][b]=cost[b][a]=999;
56. }
57. printf("\n\tMinimum cost = %d\n",mincost);
58. getch();
59.
60. }
61. int find(int i)
62. {
63. while(parent[i])
64. i=parent[i];
65. return i;
66. }
67. int uni(int i,int j)
68. {
69. if(i!=j)
70. {
71. parent[j]=i;
72. return 1;
73. }
74. return 0;
75. }
output