diff --git a/java/1584-Min-Cost-to-Connect-All-Points.java b/java/1584-Min-Cost-to-Connect-All-Points.java index e18e93bf5..b02a3f029 100644 --- a/java/1584-Min-Cost-to-Connect-All-Points.java +++ b/java/1584-Min-Cost-to-Connect-All-Points.java @@ -1,129 +1,35 @@ -class Edge { - public int source; - public int destination; - public int weight; // manhattan distance - - public Edge(int s, int d, int w){ - this.source = s; - this.destination = d; - this.weight = w; - } - - @Override - public String toString() { - return "Edge(u=" + source + ", v=" + destination + ", w=" + weight + ")"; - } -} - -class DisjointSet { - private int[] roots; - private int[] ranks; - - public DisjointSet(int n) { - this.roots = new int[n]; - this.ranks = new int[n]; - - // intializing - for(int i=0; i getEdges(int[][] points) { - int n = points.length; - List edges = new ArrayList<>(); - - // edge case - if(n <= 1) - return edges; - - for(int i=0; i<(n - 1); i++){ - for(int j=i+1; j edges, int numVertices) { - DisjointSet ds = new DisjointSet(numVertices); - int minCost = 0, numEdgesTaken = 0; - - for(Edge edge: edges){ - if(ds.areDisjoint(edge.source, edge.destination)){ - ds.union(edge.source, edge.destination); - numEdgesTaken++; - minCost += edge.weight; - } + // Time Complexity: O(N^2 log(N)) where N is the length of points. N^2 comes from the fact we need to find the distance between a currNode and every other node to pick the shortest distance. log(N) comes from Priority Queue + // Space Complexity: O(N^2) + public int minCostConnectPoints(int[][] points) { + PriorityQueue pq = new PriorityQueue<>((a,b) -> a[0] - b[0]); // edge weight, the index of next node + pq.offer(new int[]{0,0}); + int len = points.length; + Set visited = new HashSet<>(); + int cost = 0; + + // When visited.size() == points.len meaning that all the nodes has been connected. + while(visited.size() < len){ + int[] arr = pq.poll(); - if(numEdgesTaken == (numVertices - 1)) // tree is formed, early exit - break; + int weight = arr[0]; + int currNode = arr[1]; + + if(visited.contains(currNode)) + continue; + + visited.add(currNode); + cost += weight; + + for(int nextNode = 0; nextNode < len; nextNode++){ + if(!visited.contains(nextNode)){ + int nextWeight = Math.abs(points[nextNode][0] - points[currNode][0]) + Math.abs(points[nextNode][1] - points[currNode][1]); + pq.offer(new int[]{nextWeight, nextNode}); + } + } } - return minCost; - } - - public int minCostConnectPoints(int[][] points) { - // edge cases - if(isEdgeCase(points)) - return 0; - // edges - List edges = getEdges(points); - // sort the edges in ascending order - edges.sort((x1, x2) -> (x1.weight - x2.weight)); - - // Kruskals algorithm for MST [Union Find] - return getCostMST(edges, points.length); + return cost; } -} \ No newline at end of file +}