From b95350d70a5eb213ff0ff78c2e646ff29d4d711c Mon Sep 17 00:00:00 2001 From: Mahim Mahbub Date: Thu, 28 Jul 2022 00:36:12 +0600 Subject: [PATCH] 1584. Min Cost to connect all points in Java --- java/1584-Min-Cost-to-Connect-All-Points.java | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 java/1584-Min-Cost-to-Connect-All-Points.java diff --git a/java/1584-Min-Cost-to-Connect-All-Points.java b/java/1584-Min-Cost-to-Connect-All-Points.java new file mode 100644 index 000000000..e18e93bf5 --- /dev/null +++ b/java/1584-Min-Cost-to-Connect-All-Points.java @@ -0,0 +1,129 @@ +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; + } + + if(numEdgesTaken == (numVertices - 1)) // tree is formed, early exit + break; + } + 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); + } +} \ No newline at end of file