File tree Expand file tree Collapse file tree 2 files changed +60
-1
lines changed Expand file tree Collapse file tree 2 files changed +60
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,351 LeetCode solutions in JavaScript
1
+ # 1,352 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1173
1173
1531|[ String Compression II] ( ./solutions/1531-string-compression-ii.js ) |Hard|
1174
1174
1534|[ Count Good Triplets] ( ./solutions/1534-count-good-triplets.js ) |Easy|
1175
1175
1535|[ Find the Winner of an Array Game] ( ./solutions/1535-find-the-winner-of-an-array-game.js ) |Medium|
1176
+ 1536|[ Minimum Swaps to Arrange a Binary Grid] ( ./solutions/1536-minimum-swaps-to-arrange-a-binary-grid.js ) |Medium|
1176
1177
1550|[ Three Consecutive Odds] ( ./solutions/1550-three-consecutive-odds.js ) |Easy|
1177
1178
1551|[ Minimum Operations to Make Array Equal] ( ./solutions/1551-minimum-operations-to-make-array-equal.js ) |Medium|
1178
1179
1566|[ Detect Pattern of Length M Repeated K or More Times] ( ./solutions/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1536. Minimum Swaps to Arrange a Binary Grid
3
+ * https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and
7
+ * swap them.
8
+ *
9
+ * A grid is said to be valid if all the cells above the main diagonal are zeros.
10
+ *
11
+ * Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot
12
+ * be valid.
13
+ *
14
+ * The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
15
+ */
16
+
17
+ /**
18
+ * @param {number[][] } grid
19
+ * @return {number }
20
+ */
21
+ var minSwaps = function ( grid ) {
22
+ const n = grid . length ;
23
+ const trailingZeros = new Array ( n ) . fill ( 0 ) ;
24
+
25
+ for ( let i = 0 ; i < n ; i ++ ) {
26
+ trailingZeros [ i ] = countTrailingZeros ( i ) ;
27
+ }
28
+
29
+ let swaps = 0 ;
30
+ for ( let i = 0 ; i < n - 1 ; i ++ ) {
31
+ const requiredZeros = n - i - 1 ;
32
+ let found = false ;
33
+
34
+ for ( let j = i ; j < n ; j ++ ) {
35
+ if ( trailingZeros [ j ] >= requiredZeros ) {
36
+ found = true ;
37
+ for ( let k = j ; k > i ; k -- ) {
38
+ [ trailingZeros [ k ] , trailingZeros [ k - 1 ] ] = [ trailingZeros [ k - 1 ] , trailingZeros [ k ] ] ;
39
+ swaps ++ ;
40
+ }
41
+ break ;
42
+ }
43
+ }
44
+
45
+ if ( ! found ) return - 1 ;
46
+ }
47
+
48
+ return swaps ;
49
+
50
+ function countTrailingZeros ( row ) {
51
+ let count = 0 ;
52
+ for ( let j = n - 1 ; j >= 0 ; j -- ) {
53
+ if ( grid [ row ] [ j ] === 0 ) count ++ ;
54
+ else break ;
55
+ }
56
+ return count ;
57
+ }
58
+ } ;
You can’t perform that action at this time.
0 commit comments