|
| 1 | +--- |
| 2 | +id: kruskal's |
| 3 | +title: Kruskal's Graph Algorithm |
| 4 | +sidebar_label: Kruskal's Algorithm |
| 5 | +tags: |
| 6 | + - dsa |
| 7 | + - data-structures |
| 8 | + - graph |
| 9 | + - graph-traversal |
| 10 | + - algorithm |
| 11 | + - javascript |
| 12 | + - python |
| 13 | + - c++ |
| 14 | + - java |
| 15 | + - Minimum Spanning Tree |
| 16 | + - programming |
| 17 | + - tutorial |
| 18 | +sidebar_position: 3 |
| 19 | +--- |
| 20 | +Kruskal's algorithm is a popular method used to find the minimum spanning tree (MST) of a connected, undirected graph. A minimum spanning tree is a subset of the edges in a graph that connects all the vertices together, wihout any cycles, and with minimum possible total edge weight. |
| 21 | +### Key Concepts: |
| 22 | +* Edge Selection: The algorithm picks the smallest weight edge first and uses a greedy approach to ensure the overall minimum weight for the spanning tree. |
| 23 | +* Cycle Detection: To check efficiently if adding a new edge forms a cycle, the algorithm uses union-find (Disjoint set union) function for that. |
| 24 | +### To find MST using Kruskal's algorithm |
| 25 | +Following steps are used to find the MST: |
| 26 | +1. Sort the edges in ascending order of their weight. |
| 27 | +2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If the cycle is not formed, include this edge. Else, discard it. |
| 28 | +3. Repeat step 2 until there are (V-1) edges in the spanning tree. |
| 29 | +### Implementation: |
| 30 | + |
| 31 | + |
| 32 | +Program for the Kruskal's algorithm: |
| 33 | + |
| 34 | +<Tabs> |
| 35 | + <TabItem value="C++" label="C++"> |
| 36 | + ```Cpp showLineNumbers |
| 37 | + //kruskals algorithm |
| 38 | +#include<iostream> |
| 39 | +#include<vector> |
| 40 | +#define I INT32_MAX |
| 41 | +using namespace std; |
| 42 | +void Union(int u, int v,vector<int>&s)// here u and v are the head of two sets |
| 43 | +{ |
| 44 | + // the one with more child will become the ultimate head |
| 45 | + if (s[u]<s[v])//s is the array where sets are stored |
| 46 | + { |
| 47 | + s[u]=s[u]+s[v]; |
| 48 | + s[v]=u; |
| 49 | + } |
| 50 | + else |
| 51 | + { |
| 52 | + s[v]=s[u]+s[v]; |
| 53 | + s[u]=v; |
| 54 | + } |
| 55 | + |
| 56 | +} |
| 57 | +// write a find function to find the parent of any node |
| 58 | +int find(int u,vector<int>&s)// u is the element whose parent we need to find |
| 59 | +{ |
| 60 | + int x=u; |
| 61 | + int v=0; |
| 62 | + while(s[x]>0) |
| 63 | + { |
| 64 | + x=s[x]; |
| 65 | + } |
| 66 | + |
| 67 | + return x; |
| 68 | +} |
| 69 | +vector<vector<int>> kruskals_algo(vector<vector<int>>&G,int n,int a) |
| 70 | +{ |
| 71 | + vector<int>set(a,-1); |
| 72 | + vector<int>included(n,0); |
| 73 | + vector<vector<int>>sol(2,vector<int>(a-1)); |
| 74 | + int i=0,j,k,min,u,v; |
| 75 | + while(i<a-1) |
| 76 | + { |
| 77 | + min=I; |
| 78 | + for (j=0;j<n;j++) |
| 79 | + { |
| 80 | + if (included[j]==0 && G[2][j]<min) |
| 81 | + { |
| 82 | + min=G[2][j]; |
| 83 | + k=j; |
| 84 | + u=G[0][j]; |
| 85 | + v=G[1][j]; |
| 86 | + } |
| 87 | + } |
| 88 | + //cout<<"out"<<endl; |
| 89 | + int x=find(u,set),y=find(v,set); |
| 90 | + if (x!=y) |
| 91 | + { |
| 92 | + sol[0][i]=u; |
| 93 | + sol[1][i]=v; |
| 94 | + Union(x,y,set); |
| 95 | + i++; |
| 96 | + } |
| 97 | + included[k]=1; |
| 98 | + // cout<<"worked"<<endl; |
| 99 | + } |
| 100 | + //cout<<"worked"<<endl; |
| 101 | + return sol; |
| 102 | +} |
| 103 | +int main() |
| 104 | +{ |
| 105 | + int n,a; |
| 106 | + cout<<"Enter the number of edges: "; |
| 107 | + cin>>n; |
| 108 | + cout<<"Enter the number of vertexes: "; |
| 109 | + cin>>a; |
| 110 | + vector<vector<int>>G(3,vector<int>(n)); |
| 111 | + for (int i=0;i<3;i++) |
| 112 | + { |
| 113 | + for (int j=0;j<n;j++) |
| 114 | + cin>>G[i][j]; |
| 115 | + } |
| 116 | + vector<vector<int>>res=kruskals_algo(G,n,a); |
| 117 | + cout<<"Kruskals path is: "<<endl; |
| 118 | + for (int i=0;i<2;i++) |
| 119 | + { |
| 120 | + for (int j=0;j<a-1;j++) |
| 121 | + cout<<res[i][j]<<" "; |
| 122 | + cout<<endl; |
| 123 | + } |
| 124 | + return 0; |
| 125 | +} |
| 126 | + ``` |
| 127 | +</TabItem> |
| 128 | +
|
| 129 | +<TabItem value="Python" label="Python"> |
| 130 | +```Python showLineNumbers |
| 131 | +import sys |
| 132 | +
|
| 133 | +def union(u, v, s): |
| 134 | + if s[u] < s[v]: |
| 135 | + s[u] += s[v] |
| 136 | + s[v] = u |
| 137 | + else: |
| 138 | + s[v] += s[u] |
| 139 | + s[u] = v |
| 140 | +
|
| 141 | +def find(u, s): |
| 142 | + x = u |
| 143 | + while s[x] > 0: |
| 144 | + x = s[x] |
| 145 | + return x |
| 146 | +
|
| 147 | +def kruskals_algo(G, n, a): |
| 148 | + set = [-1] * a |
| 149 | + included = [0] * n |
| 150 | + sol = [[0] * (a - 1) for _ in range(2)] |
| 151 | + i = 0 |
| 152 | + while i < a - 1: |
| 153 | + min = sys.maxsize |
| 154 | + for j in range(n): |
| 155 | + if included[j] == 0 and G[2][j] < min: |
| 156 | + min = G[2][j] |
| 157 | + k = j |
| 158 | + u = G[0][j] |
| 159 | + v = G[1][j] |
| 160 | + x = find(u, set) |
| 161 | + y = find(v, set) |
| 162 | + if x != y: |
| 163 | + sol[0][i] = u |
| 164 | + sol[1][i] = v |
| 165 | + union(x, y, set) |
| 166 | + i += 1 |
| 167 | + included[k] = 1 |
| 168 | + return sol |
| 169 | +
|
| 170 | +if __name__ == "__main__": |
| 171 | + n = int(input("Enter the number of edges: ")) |
| 172 | + a = int(input("Enter the number of vertices: ")) |
| 173 | + G = [list(map(int, input().split())) for _ in range(3)] |
| 174 | + res = kruskals_algo(G, n, a) |
| 175 | + print("Kruskal's path is: ") |
| 176 | + for i in range(2): |
| 177 | + print(" ".join(map(str, res[i]))) |
| 178 | +
|
| 179 | +``` |
| 180 | +</TabItem> |
| 181 | + |
| 182 | +<TabItem value="Java" label="Java"> |
| 183 | +``` jsx showLineNumbers |
| 184 | +import java.util.*; |
| 185 | + |
| 186 | +public class KruskalsAlgorithm { |
| 187 | + static void union(int u, int v, int[] s) { |
| 188 | + if (s[u] < s[v]) { |
| 189 | + s[u] += s[v]; |
| 190 | + s[v] = u; |
| 191 | + } else { |
| 192 | + s[v] += s[u]; |
| 193 | + s[u] = v; |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + static int find(int u, int[] s) { |
| 198 | + int x = u; |
| 199 | + while (s[x] > 0) { |
| 200 | + x = s[x]; |
| 201 | + } |
| 202 | + return x; |
| 203 | + } |
| 204 | + |
| 205 | + static int[][] kruskals_algo(int[][] G, int n, int a) { |
| 206 | + int[] set = new int[a]; |
| 207 | + Arrays.fill(set, -1); |
| 208 | + int[] included = new int[n]; |
| 209 | + int[][] sol = new int[2][a - 1]; |
| 210 | + int i = 0; |
| 211 | + while (i < a - 1) { |
| 212 | + int min = Integer.MAX_VALUE; |
| 213 | + int u = 0, v = 0, k = 0; |
| 214 | + for (int j = 0; j < n; j++) { |
| 215 | + if (included[j] == 0 && G[2][j] < min) { |
| 216 | + min = G[2][j]; |
| 217 | + k = j; |
| 218 | + u = G[0][j]; |
| 219 | + v = G[1][j]; |
| 220 | + } |
| 221 | + } |
| 222 | + int x = find(u, set); |
| 223 | + int y = find(v, set); |
| 224 | + if (x != y) { |
| 225 | + sol[0][i] = u; |
| 226 | + sol[1][i] = v; |
| 227 | + union(x, y, set); |
| 228 | + i++; |
| 229 | + } |
| 230 | + included[k] = 1; |
| 231 | + } |
| 232 | + return sol; |
| 233 | + } |
| 234 | + |
| 235 | + public static void main(String[] args) { |
| 236 | + Scanner scanner = new Scanner(System.in); |
| 237 | + System.out.print("Enter the number of edges: "); |
| 238 | + int n = scanner.nextInt(); |
| 239 | + System.out.print("Enter the number of vertices: "); |
| 240 | + int a = scanner.nextInt(); |
| 241 | + int[][] G = new int[3][n]; |
| 242 | + for (int i = 0; i < 3; i++) { |
| 243 | + for (int j = 0; j < n; j++) { |
| 244 | + G[i][j] = scanner.nextInt(); |
| 245 | + } |
| 246 | + } |
| 247 | + int[][] res = kruskals_algo(G, n, a); |
| 248 | + System.out.println("Kruskal's path is: "); |
| 249 | + for (int i = 0; i < 2; i++) { |
| 250 | + for (int j = 0; j < a - 1; j++) { |
| 251 | + System.out.print(res[i][j] + " "); |
| 252 | + } |
| 253 | + System.out.println(); |
| 254 | + } |
| 255 | + scanner.close(); |
| 256 | + } |
| 257 | +} |
| 258 | +``` |
| 259 | +</TabItem> |
| 260 | + |
| 261 | +<TabItem value="JavaScript" label="JavaScript"> |
| 262 | +``` jsx showLineNumbers |
| 263 | +function union(u, v, s) { |
| 264 | + if (s[u] < s[v]) { |
| 265 | + s[u] += s[v]; |
| 266 | + s[v] = u; |
| 267 | + } else { |
| 268 | + s[v] += s[u]; |
| 269 | + s[u] = v; |
| 270 | + } |
| 271 | +} |
| 272 | + |
| 273 | +function find(u, s) { |
| 274 | + let x = u; |
| 275 | + while (s[x] > 0) { |
| 276 | + x = s[x]; |
| 277 | + } |
| 278 | + return x; |
| 279 | +} |
| 280 | + |
| 281 | +function kruskalsAlgo(G, n, a) { |
| 282 | + let set = new Array(a).fill(-1); |
| 283 | + let included = new Array(n).fill(0); |
| 284 | + let sol = [new Array(a - 1), new Array(a - 1)]; |
| 285 | + let i = 0; |
| 286 | + while (i < a - 1) { |
| 287 | + let min = Number.MAX_SAFE_INTEGER; |
| 288 | + let u, v, k; |
| 289 | + for (let j = 0; j < n; j++) { |
| 290 | + if (included[j] === 0 && G[2][j] < min) { |
| 291 | + min = G[2][j]; |
| 292 | + k = j; |
| 293 | + u = G[0][j]; |
| 294 | + v = G[1][j]; |
| 295 | + } |
| 296 | + } |
| 297 | + let x = find(u, set); |
| 298 | + let y = find(v, set); |
| 299 | + if (x !== y) { |
| 300 | + sol[0][i] = u; |
| 301 | + sol[1][i] = v; |
| 302 | + union(x, y, set); |
| 303 | + i++; |
| 304 | + } |
| 305 | + included[k] = 1; |
| 306 | + } |
| 307 | + return sol; |
| 308 | +} |
| 309 | + |
| 310 | +function main() { |
| 311 | + const n = parseInt(prompt("Enter the number of edges: ")); |
| 312 | + const a = parseInt(prompt("Enter the number of vertices: ")); |
| 313 | + let G = []; |
| 314 | + for (let i = 0; i < 3; i++) { |
| 315 | + G.push(prompt(`Enter row ${i} of graph:`).split(' ').map(Number)); |
| 316 | + } |
| 317 | + let res = kruskalsAlgo(G, n, a); |
| 318 | + console.log("Kruskal's path is: "); |
| 319 | + for (let i = 0; i < 2; i++) { |
| 320 | + console.log(res[i].join(' ')); |
| 321 | + } |
| 322 | +} |
| 323 | + |
| 324 | +main(); |
| 325 | +``` |
| 326 | +</TabItem> |
| 327 | +</Tabs> |
| 328 | + |
| 329 | +Output:<br /> |
| 330 | + |
| 331 | +``` |
| 332 | +/*input is in the format row one u, row two v and row three weight between u and v*/ |
| 333 | +Enter the number of edges: 8 |
| 334 | +Enter the number of vertexes: 7 |
| 335 | +0 0 0 1 1 3 6 4 |
| 336 | +1 3 6 2 4 4 4 5 |
| 337 | +2 3 4 3 2 5 6 7 |
| 338 | +Kruskals path is: |
| 339 | +0 1 0 1 0 4 |
| 340 | +1 4 3 2 6 5 |
| 341 | +
|
| 342 | +``` |
| 343 | +### Time and Space Complexity: |
| 344 | +* Time complexity: The time complexity of kruskal's algorithm depends on two operations i.e. sorting of all edges and union-find operation.Thus, the overall time complexity is: $O(ElogV)$ |
| 345 | +* Space complexity: The space complexity of kruskal's algorithm includes storage for edges, union-find data structure and storage for the MST. Thus the overall space complexity is: $O(E+V)$ |
0 commit comments