We have a two dimensional matrix Awhere each value is0or1.

A move consists of choosing any row or column, and toggling each value in that row or column: changing all0s to1s, and all1s to0s.

After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.

Return the highest possible score.

Note:

  1. 1 <= A.length <= 20
  2. 1 <= A[0].length <= 20
  3. A[i][j] is0or1.

这道题也是贪心算法,我们可以做的操作是对一行或者一列取反,对于一行只要第一个数是0,就有必要取反,如果是1就不用取反。对于一列,如果1比0多,不用取反,0比1多则需要取反

class Solution {
    public int matrixScore(int[][] A) {
        int res = 0;
        int m = A.length;
        int n = A[0].length;

        for(int i = 0; i < m; i++) {
            if(A[i][0] == 0)
                flipRow(A, i);
        }

        for(int i = 0; i < n; i++){
            int count = 0;
            for(int j = 0; j < m; j++) {
                if(A[j][i] == 1)
                    count++;
            }

            if(count <= m / 2)
                flipCol(A, i);
        }

        for(int i = 0; i < m; i++) {
            int num = 0;
            for(int j = 0; j < n; j++)
                num = (num << 1) + A[i][j];
            res += num;
        }

        return res;
    }

    public void flipRow(int[][] A, int row) {
        int n = A[0].length;
        for(int i = 0; i < n; i++)
            A[row][i] = A[row][i] ^ 1;
    }

    public void flipCol(int[][] A, int col) {
        int m = A.length;
        for(int i = 0; i < m; i++)
            A[i][col] = A[i][col] ^ 1;
    }
}

results matching ""

    No results matching ""