File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
src/1536-minimum-swaps-to-arrange-a-binary-grid Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } grid
3
+ * @return {number }
4
+ */
5
+
6
+ // HELP:
7
+ var minSwaps = function ( grid ) {
8
+ if ( grid . length == 1 ) return 0 ;
9
+ const n = grid . length ;
10
+ const dp = grid . map ( ( g ) => g . lastIndexOf ( 1 ) ) ; // 求每一行最右边1出现的位置 比如[2,1,0]
11
+
12
+ let res = 0 ;
13
+ // 从第0行开始遍历,分别求每一行满足题意下最少交换次数
14
+ for ( let i = 0 ; i < n ; i ++ ) {
15
+ if ( dp [ i ] <= i ) continue ; // 如果 dp[i] <= i 说明该行从右往左出现的0的个数满足合格网格。
16
+
17
+ let t = - 1 ;
18
+ // 求该行下面所有行最早出现的满足该行为合格网格的行
19
+ for ( let j = i + 1 ; j < n ; j ++ ) {
20
+ if ( dp [ j ] <= i ) {
21
+ t = j ;
22
+ break ;
23
+ }
24
+ }
25
+ if ( t === - 1 ) return - 1 ;
26
+
27
+ // 将找到的行t和i交换,并统计交换次数
28
+ for ( let j = t ; j > i ; j -- ) {
29
+ [ dp [ j ] , dp [ j - 1 ] ] = [ dp [ j - 1 ] , dp [ j ] ] ;
30
+ res ++ ;
31
+ }
32
+ }
33
+
34
+ return res ;
35
+ } ;
You can’t perform that action at this time.
0 commit comments