
Input: grid =[[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]Output: -1Explanation: All rows are similar, swaps have no effect on the grid.
For each row i, we need at least n-i-1 trailing zeros (zeros to the right of the diagonal) to make the grid valid. We can greedily find the nearest row below with enough trailing zeros and swap it up, counting the swaps. If no such row exists, it’s impossible.
classSolution {
funminSwaps(grid: Array<IntArray>): Int {
val n = grid.size
val zeros = IntArray(n)
for (i in0 until n) {
var cnt = 0for (j in n-1 downTo 0) {
if (grid[i][j] ==0) cnt++elsebreak }
zeros[i] = cnt
}
var ans = 0for (i in0 until n) {
val need = n-i-1var j = i
while (j < n && zeros[j] < need) j++if (j == n) return -1while (j > i) {
zeros[j] = zeros[j-1].also { zeros[j-1] = zeros[j] }
ans++ j-- }
}
return ans
}
}
classSolution:
defminSwaps(self, grid: list[list[int]]) -> int:
n = len(grid)
zeros = [0]*n
for i in range(n):
cnt =0for j in range(n-1, -1, -1):
if grid[i][j] ==0: cnt +=1else: break zeros[i] = cnt
ans =0for i in range(n):
need = n-i-1 j = i
while j < n and zeros[j] < need: j +=1if j == n: return-1while j > i:
zeros[j], zeros[j-1] = zeros[j-1], zeros[j]
ans +=1 j -=1return ans
impl Solution {
pubfnmin_swaps(grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
letmut zeros =vec![0; n];
for i in0..n {
letmut cnt =0;
for j in (0..n).rev() {
if grid[i][j] ==0 { cnt +=1; } else { break; }
}
zeros[i] = cnt;
}
letmut ans =0;
for i in0..n {
let need = n-i-1;
letmut j = i;
while j < n && zeros[j] < need { j +=1; }
if j == n { return-1; }
while j > i {
zeros.swap(j, j-1);
ans +=1;
j -=1;
}
}
ans
}
}