Skip to content

Commit ea49537

Browse files
committed
Add solution #1584
1 parent f554a0a commit ea49537

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,384 LeetCode solutions in JavaScript
1+
# 1,385 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1209,6 +1209,7 @@
12091209
1579|[Remove Max Number of Edges to Keep Graph Fully Traversable](./solutions/1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.js)|Hard|
12101210
1582|[Special Positions in a Binary Matrix](./solutions/1582-special-positions-in-a-binary-matrix.js)|Easy|
12111211
1583|[Count Unhappy Friends](./solutions/1583-count-unhappy-friends.js)|Medium|
1212+
1584|[Min Cost to Connect All Points](./solutions/1584-min-cost-to-connect-all-points.js)|Medium|
12121213
1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy|
12131214
1657|[Determine if Two Strings Are Close](./solutions/1657-determine-if-two-strings-are-close.js)|Medium|
12141215
1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy|
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 1584. Min Cost to Connect All Points
3+
* https://leetcode.com/problems/min-cost-to-connect-all-points/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array points representing integer coordinates of some points on a 2D-plane,
7+
* where points[i] = [xi, yi].
8+
*
9+
* The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between
10+
* them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
11+
*
12+
* Return the minimum cost to make all points connected. All points are connected if there is
13+
* exactly one simple path between any two points.
14+
*/
15+
16+
/**
17+
* @param {number[][]} points
18+
* @return {number}
19+
*/
20+
var minCostConnectPoints = function(points) {
21+
const n = points.length;
22+
const minCost = Array(n).fill(Infinity);
23+
const visited = new Set();
24+
let result = 0;
25+
26+
minCost[0] = 0;
27+
28+
for (let i = 0; i < n; i++) {
29+
let minIdx = -1;
30+
let minVal = Infinity;
31+
32+
for (let j = 0; j < n; j++) {
33+
if (!visited.has(j) && minCost[j] < minVal) {
34+
minVal = minCost[j];
35+
minIdx = j;
36+
}
37+
}
38+
39+
if (minIdx === -1) break;
40+
41+
visited.add(minIdx);
42+
result += minVal;
43+
44+
for (let j = 0; j < n; j++) {
45+
if (!visited.has(j)) {
46+
const cost = Math.abs(points[minIdx][0] - points[j][0])
47+
+ Math.abs(points[minIdx][1] - points[j][1]);
48+
minCost[j] = Math.min(minCost[j], cost);
49+
}
50+
}
51+
}
52+
53+
return result;
54+
};

0 commit comments

Comments
 (0)