782. Transform to Chessboard (Hard) - TengnanYao/daily_leetcode GitHub Wiki

class Solution:
    def movesToChessboard(self, board: List[List[int]]) -> int:
        n = len(board)
        rows, cols = set(), {0}
        for i in range(n):
            if board[0][i] == 1:
                rows.add(i)
        if n % 2 == 0 and len(rows) != n // 2:
            return -1
        if n % 2 == 1 and len(rows) != n // 2 and len(rows) != n // 2 + 1:
            return -1
        for i in range(1, n):
            case1 = all(board[i][j] == 1 for j in rows) and all(board[i][j] == 0 for j in range(n) if j not in rows)
            case2 = all(board[i][j] == 0 for j in rows) and all(board[i][j] == 1 for j in range(n) if j not in rows)
            if not (case1 or case2):
                return -1
            if case1:
                cols.add(i)
        if n % 2 == 0 and len(cols) != n // 2:
            return -1
        if n % 2 == 1 and len(cols) != n // 2 and len(cols) != n // 2 + 1:
            return -1
        count1 = sum(x % 2 == 0 for x in rows)
        count2 = sum(x % 2 == 0 for x in cols)
        if n % 2 == 0:
            return min(count1, len(rows) - count1) + min(count2, len(cols) - count2)
        else:
            r = count1 if len(rows) == n // 2 else len(rows) - count1
            c = count2 if len(cols) == n // 2 else len(cols) - count2
            return r + c