Minimum Swaps to Arrange a Binary Grid
Real-world version: Row Shuffles to Clear the DiagonalThe statement here is our own: the same inputs, outputs and technique.
A stencil sheet is a square grid of 0s and 1s given as grid, with n rows and n columns.
One shuffle swaps two rows that sit next to each other. The sheet is usable when every cell strictly above the main diagonal holds a 0, that is when grid[i][j] is 0 for every j greater than i.
Return the fewest shuffles that make the sheet usable, or -1 when no number of shuffles can. A shuffle count is never negative, so -1 can only mean it is impossible.
Examples
Example 1
- Input
- grid = [[0, 0, 0], [1, 1, 0], [1, 0, 0]]
- Output
- 0
The top row already has the two trailing zeros it needs. The second row needs one trailing zero and ends in a 1, so the third row is brought up past it.
Example 2
- Input
- grid = [[0, 1], [0, 1]]
- Output
- -1
Both rows end in a 1, so neither can sit on top where a trailing zero is needed, and no shuffle helps.
Example 3
- Input
- grid = [[0, 0], [0, 0]]
- Output
- 0
Every cell above the diagonal already holds a 0, so the sheet is usable as it stands.
Constraints
- 1 <= grid.length <= 200
- Every row of grid has length grid.length
- 0 <= grid[i][j] <= 1
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def row_shuffles(grid: list[list[int]]) -> int:public int rowShuffles(int[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Score After Flipping MatrixReal-world version: Maximum Relay Cabinet TotalMedium
- Largest Submatrix With RearrangementsReal-world version: Widest Block After Reordering ColumnsMedium
- Maximum Matrix SumReal-world version: Turning Signs in Pairs on the GridMedium
- Can Place FlowersReal-world version: Blade Spacing in the RackEasy