Transform to Chessboard

You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.

Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.

A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.

Example 1
0 1 1 0
0 1 1 0
1 0 0 1
1 0 0 1
Inputboard = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output2
One potential sequence uses two moves: swap the first and second column, then swap the second and third row.
Example 2
0 1
1 0
Inputboard = [[0,1],[1,0]]
Output0
The board is already a valid chessboard, including the variant with 0 in the top-left corner.

Constraints

  • n == board.length
  • n == board[i].length
  • 2 <= n <= 30
  • board[i][j] is either 0 or 1.

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate