shriyanshi24jindal

Minimum Spanning Tree

Mar 30th, 2026
132
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 12.60 KB | None | 0 0
  1. class Pair {
  2. int vertex;
  3. int weight;
  4.  
  5. Pair(int weight, int vertex)
  6. {
  7. this.vertex = vertex;
  8. this.weight = weight;
  9. }
  10. }
  11.  
  12. class Solution {
  13. /**
  14.   * Start from any node and keep adding the minimum weight edge that connects a visited node to an unvisited node.
  15.   * Step 1: Build Adjacency List
  16.   * Step 2: Use a Min Heap (Priority Queue)
  17.   * -- This ensures we always pick the minimum weight edge
  18.   * -- Each entry in PQ = (weight, node)
  19.   * Step 3: Start from Node 0, Start with node 0 and Weight = 0 (no cost to start)
  20.   * Step 4: Maintain Visited Array and sum as 0
  21.   * Step 5: Main Loop (Core of Prim’s)
  22.   * -- Extract minimum edge
  23.   * -- Always picks the smallest weight edge available
  24.   * -- Skip if already visited, Avoids revisiting nodes (cycle prevention)
  25.   * -- Include this edge in MST
  26.   * -- Add its weight to total cost
  27.   * -- Explore neighbors and Push all adjacent edges into PQ, Only if neighbor is not visited
  28.   * Step 6: Return sum of all edges
  29.   */
  30. public int spanningTree(int V, int[][] edges) {
  31. // Step-1 Create an adjacency list
  32. ArrayList<ArrayList<Pair>> adj = new ArrayList<>();
  33. for(int i=0; i<V; i++)
  34. {
  35. adj.add(new ArrayList<Pair>());
  36. }
  37.  
  38. for(int[] edge : edges)
  39. {
  40. int u = edge[0];
  41. int v = edge[1];
  42. int w = edge[2];
  43.  
  44. adj.get(u).add(new Pair(w, v));
  45. adj.get(v).add(new Pair(w, u)); // undirected
  46. }
  47.  
  48. // Step-2 Create a visited array
  49. boolean[] visited = new boolean[V];
  50.  
  51. // Step-3 Define a min-heap <weight, node>
  52. PriorityQueue<Pair> pq = new PriorityQueue<>( (x,y) -> Integer.compare(x.weight, y.weight));
  53. pq.offer(new Pair(0, 0));
  54.  
  55. int sum = 0;
  56. while(!pq.isEmpty())
  57. {
  58. Pair pair = pq.poll();
  59. int weight = pair.weight;
  60. int currentNode = pair.vertex;
  61.  
  62. if(visited[currentNode])
  63. continue;
  64.  
  65. visited[currentNode] = true;
  66. sum += weight;
  67.  
  68. // traverse the neighbour nodes
  69. for(Pair neighbour : adj.get(currentNode))
  70. {
  71. if(visited[neighbour.vertex] == false)
  72. {
  73. pq.offer(new Pair(neighbour.weight, neighbour.vertex));
  74. }
  75. }
  76. }
  77. return sum;
  78. }
  79. }
RAW Paste Data Copied