1536. Minimum Swaps to Arrange a Binary Grid
Description
Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
Example 1:

Input: grid = [[0,0,1],[1,1,0],[1,0,0]] Output: 3
Example 2:

Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]] Output: -1 Explanation: All rows are similar, swaps have no effect on the grid.
Example 3:

Input: grid = [[1,0,0],[1,1,0],[1,1,1]] Output: 0
Constraints:
n == grid.length== grid[i].length1 <= n <= 200grid[i][j]is either0or1
Solutions
Solution: Greedy
- Time complexity: O(n2)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[][]} grid
* @return {number}
*/
const minSwaps = function (grid) {
const n = grid.length;
const rows = grid.map(row => n - row.lastIndexOf(1) - 1);
let result = 0;
const findSwapRow = (row, needZeros) => {
for (let index = row; index < n; index++) {
if (rows[index] >= needZeros) {
return index;
}
}
return -1;
};
for (let row = 0; row < n - 1; row++) {
const needZeros = n - row - 1;
const swapRow = findSwapRow(row, needZeros);
if (swapRow === -1) return -1;
for (let index = swapRow; index > row; index--) {
[rows[index - 1], rows[index]] = [rows[index], rows[index - 1]];
result += 1;
}
}
return result;
};