Min Cost to Connect All Points LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} points
3
* @return {number}
4
*/
5
//By Kruskal Approach
6
let union_find, mapping_arr, count, maxCost, rank;
7
const find = (root) => {
8
if (union_find[root] === root) return root;
9
return (union_find[root] = find(union_find[root]));
10
};
11
const union = ([src, dst, d]) => {
12
let rootX = find(src);
13
let rootY = find(dst);
14
if (rootX != rootY) {
15
if (rank[rootX] < rank[rootY]) {
16
union_find[rootX] = rootY;
17
} else if (rank[rootX] > rank[rootY]) {
18
union_find[rootY] = rootX;
19
} else {
20
union_find[rootY] = rootX;
21
rank[rootX]++;
22
}
23
count--;
24
maxCost += d;
25
}
26
};
27
var minCostConnectPoints = function (points) {
28
let edges = [];
29
union_find = [];
30
rank = [];
31
maxCost = 0;
32
count = points.length;
33
for (let i = 0; i < points.length; i++) {
34
union_find[i] = i;
35
rank[i] = 1;
36
let src = points[i];
37
for (let j = i + 1; j < points.length; j++) {
38
let dst = points[j];
39
let d = Math.abs(src[0] - dst[0]) + Math.abs(src[1] - dst[1]);
40
edges.push([i, j, d]);
41
}
42
}
43
edges.sort((a, b) => a[2] - b[2]);
44
for (let i = 0; i < edges.length; i++) {
45
if (count > 1) union(edges[i]);
46
}
47

48
return maxCost;
49
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0