-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinCostToConnectAllPoints.java
629 lines (464 loc) · 17.5 KB
/
MinCostToConnectAllPoints.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package Algorithms.DisjointSetUnion;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeMap;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 28 March 2025
*
* Similar to Minimum Spanning Tree problem MST
*
* Popular Algorithms for Finding Minimum Spanning Tree MST:
* 1. Prim’s Algorithm (Greedy, uses Priority Queue) and
* 2. Kruskal's Algorithm (Greedy, uses Union-Find)
*/
public class MinCostToConnectAllPoints {
public static void main(String[] args) {
int[][] points = {{0, 0}, {2, 2}, {3, 10}, {5, 2}, {7, 0}};
System.out.println("Min cost My Approach: " + minCostConnectPointsKruskalsMyApproach(points));
System.out.println( "Min cost Kruskals MST: " + minCostConnectPointsKruskalsMST(points));
System.out.println( "Min cost Prim's MST AdjLst: " + minCostConnectPointsPrimsAdjList(points));
}
/**
PATTERNS:
---------
1) Kruskal's MST algo
2) Sort all edges by weight, with all possible combinations
3) Now trav the weights in asc order and add non-cyclic edges until we connected all nodes i.e numOfComps == 1
4) Consider i index in points as node.
*/
public static int minCostConnectPointsKruskalsMyApproach(int[][] points) {
int n = points.length;
Map<Integer, List<int[]>> map = new TreeMap<>(); // sorted order
for (int i=0; i<n; i++) {
for (int j=i+1; j<n; j++) {
int weight = dist(points[i], points[j]);
map.computeIfAbsent(weight, _-> new ArrayList<>()).add(new int[]{i,j});
}
}
par = new int[n];
rank = new int[n];
for(int i=0; i<n; i++) par[i]=i;
int count=0, comps=n;
main:
for(int i: map.keySet()) {
List<int[]> edges = map.get(i);
for(int[] edge: edges) {
if (union(edge[0], edge[1])) {
count+=i;
if (comps-- == 1) break main;
}
}
}
return count;
}
static int[] par, rank;
private static boolean union(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa == pb) return false;
if (rank[pb] < rank[pa]) par[pb]=pa;
else if(rank[pa] < rank[pb]) par[pa]=pb;
else {
par[pb]=pa;
rank[pa]++;
}
return true;
}
private static int find(int i){
if (i != par[i]) {
i = par[i] = find(par[i]);
}
return i;
}
private static int dist(int[] a, int[] b) {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}
public int minCostConnectPointsKruskalsMyApproach2(int[][] points) {
Map<Integer, Set<String> > map = new TreeMap<>();
for (int[] i: points) {
for (int[] j: points) {
if (i.equals(j)) continue;
int weight = dist2(i, j);
String edge = edge2(i,j);
String reverseEdge = edge2(j,i);
map.putIfAbsent(weight, new HashSet<>());
if (!map.get(weight).contains(reverseEdge))
map.get(weight).add(edge);
}
}
UnionFind2 uf = new UnionFind2(points);
int c=0;
main:
for(int i: map.keySet()) {
List<String> lst = new ArrayList<>(map.get(i));
for(String s: lst) {
String[] sArr = s.split(",");
String a = sArr[0] + "," + sArr[1];
String b = sArr[2] + "," + sArr[3];
if (uf.union(a,b)) {
c+=i;
if (uf.comps == 1) break main;
}
}
}
return c;
}
private int dist2(int[] a, int[] b) {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}
private String edge2(int[] a, int[] b) {
return String.format("%s,%s,%s,%s",a[0],a[1],b[0],b[1]);
}
class UnionFind2 {
Map<String, String> par = new HashMap<>();
Map<String, Integer> rank = new HashMap<>();
int comps;
UnionFind2 (int[][] points) {
for (int[] p: points) {
String s = p[0] +","+ p[1];
par.put(s,s);
rank.put(s,0);
}
comps=points.length;
}
private boolean union(String a, String b) {
String pa = find(a);
String pb = find(b);
if (pa.equals(pb)) return false;
if (rank.get(pb) < rank.get(pa)) par.put(pb, pa);
else if(rank.get(pa) < rank.get(pb)) par.put(pa, pb);
else {
par.put(pb, pa);
rank.put(pa, rank.get(pa)+1);
}
comps--;
return true;
}
private String find(String key){
if (!key.equals(par.get(key))) {
par.put(key, find(par.get(key))); // Path compression
}
return par.get(key);
}
}
public static int minCostConnectPointsKruskalsMST(int[][] points) {
int n = points.length;
List<int[]> edges = new ArrayList<>(); // [weight, node1, node2]
// Create all possible edges and calculate their Manhattan distance
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int weight = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
edges.add(new int[]{weight, i, j});
}
}
// Sort edges by weight
Collections.sort(edges, Comparator.comparingInt(a -> a[0]));
// Use Kruskal's algorithm to calculate the MST cost
return kruskalsMST(edges, n);
}
public static int kruskalsMST(List<int[]> edges, int n) {
int[] parent = new int[n];
int[] rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}
int cost = 0;
int edgesUsed = 0;
for (int[] edge : edges) {
int weight = edge[0], u = edge[1], v = edge[2];
if (union(parent, rank, u, v)) { // If union is successful (no cycle)
cost += weight;
edgesUsed++;
if (edgesUsed == n - 1) break; // MST is complete
}
}
return cost;
}
private static boolean union(int[] parent, int[] rank, int u, int v) {
int rootU = find(parent, u);
int rootV = find(parent, v);
if (rootU == rootV) return false; // Already connected
if (rank[rootU] > rank[rootV]) {
parent[rootV] = rootU;
} else if (rank[rootU] < rank[rootV]) {
parent[rootU] = rootV;
} else {
parent[rootV] = rootU;
rank[rootU]++;
}
return true;
}
private static int find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = find(parent, parent[x]); // Path compression
}
return parent[x];
}
public static int minCostConnectPointsKruskalsMST2(int[][] points) {
int n = points.length;
List<int[]> edges = new ArrayList<>(); // [weight, node1, node2]
// Create all possible edges and calculate their Manhattan distance
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int weight = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
edges.add(new int[]{weight, i, j});
}
}
// Sort edges by weight
Collections.sort(edges, Comparator.comparingInt(a -> a[0]));
// Union-Find (Disjoint Set) to detect cycles
UnionFind uf = new UnionFind(n);
int mstCost = 0;
int edgesUsed = 0;
for (int[] edge : edges) {
int weight = edge[0], u = edge[1], v = edge[2];
if (uf.union(u, v)) { // If union is successful (no cycle)
mstCost += weight;
edgesUsed++;
if (edgesUsed == n - 1) break; // MST is complete
}
}
return mstCost;
}
static class UnionFind {
private int[] parent, rank;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
}
public int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]); // Path compression
return parent[x];
}
public boolean union(int x, int y) {
int rootX = find(x), rootY = find(y);
if (rootX == rootY) return false; // Already connected
if (rank[rootX] > rank[rootY]) parent[rootY] = rootX;
else if (rank[rootX] < rank[rootY]) parent[rootX] = rootY;
else {
parent[rootY] = rootX;
rank[rootX]++;
}
return true;
}
}
/**
* Prim's Algorithm using min-heap or Frontier
*
* @TimeComplexity: O(n^2 * log(n))
* @SpaceComplexity: O(n)
*
* Here, except the root node, each node must be child for one node but it can be parent for multiple nodes
* So, mark this child as visited using array[n] or Set
*/
@SuppressWarnings({"unchecked"})
public static int minCostConnectPointsPrimsAdjList(int[][] points) {
int n = points.length;
List<int[]>[] adjList = new List[n]; // List[] will throws ==> List is a raw type. References to generic type List<E> should be parameterized
for(int i=0; i<n; i++) adjList[i]=new ArrayList<>();
// each node is connected to all other nodes, just like graph
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int weight = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]);
adjList[i].add(new int[]{j, weight});
adjList[j].add(new int[]{i, weight});
}
}
Set<Integer> visited = new HashSet<>(); // To track visited nodes in the MST
int mstCost = 0;
PriorityQueue<int[]> frontier = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); // Min-Heap: [node, weight]
frontier.add(new int[]{0, 0}); // Start from node 0 with cost 0 by considering it as root
while (visited.size() < n) {
int[] curr = frontier.poll();
int i = curr[0], weight = curr[1];
if (visited.contains(i)) continue; // Skip if already visited
visited.add(i); // Mark node as visited
mstCost += weight; // Add weight to MST cost
// Add all "i" node edges
for (int[] edge : adjList[i]) {
int v = edge[0], edgeWeight = edge[1];
if (!visited.contains(v)) frontier.add(new int[]{v, edgeWeight});
}
}
return mstCost;
}
public int minCostConnectPointsPrimsPQ(int[][] points) {
int n = points.length;
boolean[] visited = new boolean[n]; // To track visited nodes
// Min-Heap: [node, weight]
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.add(new int[]{0, 0}); // Start from node 0 with cost 0 by considering it as root
// if you want you can also save {weight, par, child}
int mstCost = 0;
int edgesUsed = 0; // above method have visitedSet which replaces both visitedArray and edgesUsed
while (!pq.isEmpty() && edgesUsed < n) { // && edgesUsed < n ---> is optional but it improves performance
int[] curr = pq.poll();
int u = curr[0], weight = curr[1];
if (visited[u]) continue;
visited[u] = true;
mstCost += weight;
edgesUsed++;
// U children
// Add all "u" node edges / children (but skip "v" node that is already) in PQ
for (int v = 0; v < n; v++) {
if (!visited[v]) {
int dist = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
pq.add(new int[]{v, dist});
}
}
}
return mstCost;
}
public int minCostConnectPointsPrimsArray(int[][] points) {
int n = points.length;
int[] key = new int[n]; // Stores minimum cost to reach each node
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0; // Start with node 0
boolean[] visited = new boolean[n]; // Tracks visited nodes
int mstCost = 0;
for (int i = 0; i < n; i++) {
int u = -1;
// Find the minimum key node not yet included in MST
for (int j = 0; j < n; j++) {
if (!visited[j] && (u == -1 || key[j] < key[u])) {
u = j;
}
}
visited[u] = true;
mstCost += key[u];
// Update the keys for neighbors
for (int v = 0; v < n; v++) {
if (!visited[v]) {
int dist = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]);
if (dist < key[v]) {
key[v] = dist;
}
}
}
}
return mstCost;
}
public int minCostConnectPointsUsingDFS(int[][] points) {
if (points.length == 0) {
return 0;
}
boolean[] visited = new boolean[points.length];
int[] cost = new int[points.length];
Arrays.fill(cost, Integer.MAX_VALUE);
int total = 0;
int next = 0;
visited[next] = true;
for (int i = points.length - 1; i > 0; --i) {
next = dfs(points, visited, cost, next);
visited[next] = true;
total += cost[next];
}
return total;
}
private int dfs(int[][] points, boolean[] visited, int[] cost, int idx) {
int min = Integer.MAX_VALUE;
int minIdx = -1;
for (int i = 0; i < points.length; ++i) {
if (visited[i]) {
continue;
}
cost[i] = Math.min(cost[i], distance(points[i], points[idx]));
if (cost[i] < min) {
minIdx = i;
min = cost[i];
}
}
return minIdx;
}
private int distance(int[] a, int[] b) {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}
/**
NOT WORKING
THOUGHTS:
---------
1) Can we assume UF rank[i] as |val| or |xi+yi|? ---> small
2) Note |xi - xj| + |yi - yj| != | (xi + yi) - (xj+yj) |
3) All points must connect, just like DSU
4) Use map instead of par[]
*/
public int minCostConnectPointsMyOldApproach(int[][] points) {
Map<Map.Entry<Integer, Integer>, Map.Entry<Integer, Integer>> map = new HashMap<>();
for (int[] p: points) {
map.put(
new AbstractMap.SimpleEntry<>(p[0], p[1]),
new AbstractMap.SimpleEntry<>(-1,-1)
);
}
for (Map.Entry<Integer, Integer> i: map.keySet()) {
int min = Integer.MAX_VALUE;
Map.Entry<Integer, Integer> need = new AbstractMap.SimpleEntry<>(-1,-1);
for (Map.Entry<Integer, Integer> j: map.keySet()) {
if (!i.equals(j) && !map.get(j).equals(i)){
int val =(
Math.abs(i.getKey() - j.getKey())
+
Math.abs(i.getValue() - j.getValue())
);
if (val < min) {
min=val;
need = j;
}
}
}
map.put(i, need);
}
System.out.println(map);
int c=0;
UF uf = new UF(map);
for (Map.Entry<Integer, Integer> i: map.keySet()) {
Map.Entry<Integer, Integer> j = map.get(i);
c+=uf.union(i,j);
System.out.println(c);
}
return c;
}
class UF {
Map<Map.Entry<Integer, Integer>, Map.Entry<Integer, Integer>> par = new HashMap<>();
Map<Map.Entry<Integer, Integer>, Integer> rank = new HashMap<>();
UF (Map<Map.Entry<Integer, Integer>, Map.Entry<Integer, Integer>> map) {
for (Map.Entry<Integer, Integer> i: map.keySet()) {
par.put(i,i);
rank.put(i,0);
}
}
private int union(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
Map.Entry<Integer, Integer> pa = find(a);
Map.Entry<Integer, Integer> pb = find(b);
if (pa.equals(pb)) return 0;
if (rank.get(pb) < rank.get(pa)) par.put(pb, pa);
else if(rank.get(pa) < rank.get(pb)) par.put(pa, pb);
else {
par.put(pb, pa);
rank.put(pa, rank.get(pa)+1);
}
int val =(
Math.abs(a.getKey() - b.getKey())
+
Math.abs(a.getValue() - b.getValue())
);
return val;
}
private Map.Entry<Integer, Integer> find(Map.Entry<Integer, Integer> k){
while(!k.equals(par.get(k))) k = par.get(k);
return k;
}
}
}