grid of zeros and ones. In one move you may swap any two rows or any two columns.
A grid is a **checkerboard** when no two cells that share a side hold the same value. The top-left corner may be either 0 or 1.
Return the minimum number of moves needed to turn the grid into a checkerboard, or -1 if it cannot be done.grid=[[1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1], [1, 1, 0, 0]] → 2
Swapping columns 1 and 2 makes every row alternate. Then swapping rows 2 and 3 (or 0 and 1) makes the columns alternate too. That is 2 swaps, and it cannot be done faster.
grid=[[1, 0, 1], [0, 1, 0], [1, 0, 1]] → 0
The grid is already a checkerboard, so nothing needs to move.
grid=[[1, 1], [0, 0]] → -1
Both cells in each row are equal, and no reordering of rows or columns can change that.
grid[i][j] is 0 or 1grid=[[1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1], [1, 1, 0, 0]]
2
Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.