#1536

Minimum Swaps to Arrange a Binary Grid

pupil · 565 · lc medium +29 · verified · 70.1% accepted · 1,012 likes · top 78%

Description

Given an n x n binary grid, each step lets you swap two adjacent rows. A grid is valid when every cell strictly above the main diagonal is 0. Return the minimum number of row swaps required to reach a valid configuration, or -1 if it is impossible.

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

Code

1
2
3