forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1584-min-cost-to-connect-all-points.ts
More file actions
36 lines (29 loc) · 1008 Bytes
/
1584-min-cost-to-connect-all-points.ts
File metadata and controls
36 lines (29 loc) · 1008 Bytes
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
function getDistance(a, b) {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}
function minCostConnectPoints(points: number[][]): number {
const n = points.length;
const visited = new Set<string>();
const minHeap = new MinPriorityQueue({ priority: (a) => a[2] });
visited.add(points[0].join(','));
for (let point of points) {
if (visited.has(point.join(','))) continue;
minHeap.enqueue([points[0], point, getDistance(points[0], point)]);
}
let result = 0;
while (visited.size < n) {
const { element: minEdge } = minHeap.dequeue();
if (visited.has(minEdge[1].join(','))) continue;
visited.add(minEdge[1].join(','));
result += minEdge[2];
for (let point of points) {
if (visited.has(point.join(','))) continue;
minHeap.enqueue([
minEdge[1],
point,
getDistance(minEdge[1], point),
]);
}
}
return result;
}