1536. Minimum Swaps to Arrange a Binary Grid
SourceWeekly Contest 200 Q3DifficultyMediumRating1880
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 1: Greedy
Thinking
Adjacent row swaps must make every row \(i\) all zeros to the right of the diagonal. Only the rightmost \(1\) in a row matters: it is legal for row \(i\) iff that index is at most \(i\). \(n\le 200\) allows a per-row greedy.
For each \(i\), among unused rows take the first whose rightmost \(1\) is at most \(i\), then bubble it to position \(i\) at cost \(k-i\). If none exists the instance is impossible. Satisfying upper rows first does not block later ones, which require fewer trailing zeros.
We process row by row. For the \(i\)-th row, the position of the last '1' must be less than or equal to \(i\). We find the first row that meets the condition in \([i, n)\), denoted as \(k\). Then, starting from the \(k\)-th row, we swap the adjacent two rows upwards until the \(i\)-th row.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n)\). Here, \(n\) is the side length of the grid.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |


