File tree 2 files changed +56
-1
lines changed
2 files changed +56
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,384 LeetCode solutions in JavaScript
1
+ # 1,385 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1209
1209
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|
1210
1210
1582|[ Special Positions in a Binary Matrix] ( ./solutions/1582-special-positions-in-a-binary-matrix.js ) |Easy|
1211
1211
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|
1212
1213
1598|[ Crawler Log Folder] ( ./solutions/1598-crawler-log-folder.js ) |Easy|
1213
1214
1657|[ Determine if Two Strings Are Close] ( ./solutions/1657-determine-if-two-strings-are-close.js ) |Medium|
1214
1215
1668|[ Maximum Repeating Substring] ( ./solutions/1668-maximum-repeating-substring.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments