Skip to main content
LeetCode 782, Hard. Topics: Array, Math, Bit Manipulation, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 27 parametrized pytest cases, and a playground notebook:

Problem

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.

Examples

Example 1
Example 2
Example 3

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026