shriyanshi24jindal

Min Cost to Connect Points

Mar 30th, 2026
124
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 12.68 KB | None | 0 0
  1. class Pair
  2. {
  3. int vertex;
  4. int weight;
  5. Pair(int weight, int vertex)
  6. {
  7. this.weight = weight;
  8. this.vertex = vertex;
  9. }
  10. }
  11.  
  12. class Solution {
  13. public int minCostConnectPoints(int[][] points) {
  14. int V = points.length;
  15.  
  16. // Step-1 Create an adjacency list: each node has (weight, neighbor)
  17. List<List<int[]>> adj = new ArrayList<>();
  18. for(int i=0; i<V; i++)
  19. {
  20. adj.add(new ArrayList<>());
  21. }
  22.  
  23. // Step-2 build edges
  24. for(int i=0; i<V; i++)
  25. {
  26. for(int j=i+1; j<V; j++)
  27. {
  28. int weight = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
  29.  
  30. adj.get(i).add(new int[]{weight, j});
  31. adj.get(j).add(new int[]{weight, i}); // undirected
  32. }
  33. }
  34.  
  35. // Step-3 Create a visited array
  36. boolean[] visited = new boolean[V];
  37.  
  38. // Step-4 Define a min-heap <weight, node>
  39. PriorityQueue<Pair> pq = new PriorityQueue<>( (x,y) -> Integer.compare(x.weight, y.weight));
  40. pq.offer(new Pair(0, 0));
  41. int sum = 0;
  42.  
  43. while(!pq.isEmpty())
  44. {
  45. Pair pair = pq.poll();
  46. int currentNode = pair.vertex;
  47. int currentWeight = pair.weight;
  48.  
  49. if(visited[currentNode])
  50. continue;
  51.  
  52. visited[currentNode] = true;
  53. sum += currentWeight;
  54.  
  55. // traverse neighbour nodes
  56. for(int[] neighbour : adj.get(currentNode))
  57. {
  58. int vertex = neighbour[1];
  59. int weight = neighbour[0];
  60. if(visited[vertex] == false)
  61. {
  62. pq.add(new Pair(weight, vertex));
  63. }
  64. }
  65. }
  66. return sum;
  67. }
  68. }
RAW Paste Data Copied