#782
Transform to Chessboard
candidate master · 1450 · lc hard +32 · verified · 51.2% accepted · 373 likes · top 40%
Description
Given an n x n binary grid board, you can swap any two rows or any two columns in a single move. Return the minimum number of moves to transform board into a valid chessboard pattern (no two adjacent cells share the same value). Return -1 if the transformation is impossible.
Example 1:
Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output: 2
Explanation: One potential sequence of moves is shown.
The first move swaps the first and second column.
The second move swaps the second and third row.
Example 2:
Input: board = [[0,1],[1,0]]
Output: 0
Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
Input: board = [[1,0],[1,0]]
Output: -1
Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
Code
1
2
3