返回题库

变为棋盘

Transform to Chessboard

专题
Algorithmic Programming / 算法编程
难度
L4
来源
Citadel

题目详情

问题:变为棋盘

考察:数组

来源:Citadel

链接:https://www.jointaro.com/interviews/questions/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:

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.

 

Constraints:

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

思路:合法棋盘只有两种行模式互补、两种列模式互补。先检查任意两行/列是否满足相同或互补,再分别计算行和列最少交换次数。

复杂度:时间 O(n^2),空间 O(n)。