其他分享
首页 > 其他分享> > 861. Score After Flipping Matrix(Leetcode每日一题-2020.12.07)

861. Score After Flipping Matrix(Leetcode每日一题-2020.12.07)

作者:互联网

Problem

We have a two dimensional matrix A where each value is 0 or 1.

A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.

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:

Example

Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Solution

class Solution {
public:
    int matrixScore(vector<vector<int>>& a) {
        //step1:翻转所有行,保证第一列全为1
        int m=a.size(),n=a[0].size();
        for (int i=0;i<m;i++)
        {
            if (a[i][0]!=1)
            {
                //翻转该行
                for (int j=0;j<n;j++)
                {
                    a[i][j]=!a[i][j];
                }
            }
        }
        //step2:从第二列开始,检查该列的1的数量是否大于等于0,如果不是,则翻转该列
        for (int j=1;j<n;j++)
        {
            int count=0;
            for (int i=0;i<m;i++)
            {
                if (a[i][j]) count++;
            }
            if (count<(m+1)/2)
            {
                for (int i=0;i<m;i++)
                {
                    a[i][j]=!a[i][j];
                }
            }
        }
        //step3:计算结果并返回
        int num=0;
        for(int j=0;j<n;j++)
        {
            int temp=pow(2,n-j-1);
            for (int i=0;i<m;i++)
            {
                num+=a[i][j]*temp;
            }
        }
        return num;
    }
};

标签:count,matrix,861,翻转,After,int,num,row,Matrix
来源: https://blog.csdn.net/sjt091110317/article/details/110839806