n × n grid board of zeros and ones. In one move you may swap two adjacent rows.
The grid is valid when every cell strictly above the main diagonal (running from the top-left to the bottom-right corner) is zero. In other words, in row i (0-indexed) every cell from column i + 1 onward must be zero.
Return the smallest number of moves that makes the grid valid, or -1 if that is impossible.board=[[1, 1, 0], [1, 0, 0], [0, 1, 1]] → 1
One swap of the first two rows gives [[1, 0, 0], [1, 1, 0], [0, 1, 1]]. The last row may hold anything, since it has no cells above the diagonal.
board=[[0, 1], [0, 1]] → -1
Both rows end in 1, but the top row must have a 0 there. The answer is -1.
board=[[1]] → 0
board[i][j] is 0 or 1board=[[1, 1, 0], [1, 0, 0], [0, 1, 1]]
1
Run checks the first 3 tests in your browser. Submit checks all 73 tests on the server, hidden ones included.