1. 程式人生 > >861. Score After Flipping Matrix(python+cpp)

861. Score After Flipping Matrix(python+cpp)

題目:

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.
Example 1:

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  

Note:
1 <= A.length <= 20
1 <= A[0].length <= 20 A[i][j] is 0 or 1.

解釋:
方法:
1.對於開頭為0的行,進行翻轉
2.對於0的數目大於1的數目的列,進行翻轉
翻轉可以通過與1異或實現,也可以通過用1減去實現
python程式碼:

class Solution(object):
    def matrixScore(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
         
        if not A:
            return 0
        m=len(A)
        n=len(A[0])
        def fliprow(r):
            for i in range(n):
                A[r][i]^=1
        def
flipcol(c): for i in range(m): A[i][c]^=1 #第一步,對於開頭為0的行,翻轉 for i in range(m): if A[i][0]==0: fliprow(i) #第二步,對於0的數目大於1的數目的列,進行翻轉,不處理第0列,因為經過第一步以後,第0列全是1 #對於列進行遍歷 for i in range(1,n): sumofone=0 for j in range(m): sumofone+=A[j][i] if 2*sumofone<m : flipcol(i) #求和 _sum=0 for i in range(m): _sum+=int(''.join(map(str,A[i])),2) return _sum

c++程式碼:

#inlcude<cmath>
class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {
        int m=A.size();
        if(m==0)
            return 0;
        int n=A[0].size();
        //對於第一列為0的行進行翻轉
        for(int i=0;i<m;i++)
            if (A[i][0]==0)
                flipr(i,A);
        //對於0的個數大於1的個數的列,翻轉
        for(int i=0;i<n;i++)
        {
            int sumOne=0;
            for (int j=0;j<m;j++)
                if (A[j][i]==1)
                    sumOne++;
            if (2*sumOne<m)
                flipc(i,A);
        }
        //求和
        int _sum=0;
        for (int i=0;i<m;i++)
        {
            int base=pow(2,n-1);
            for (int j=0;j<n;j++)
            {
                 _sum+=base*A[i][j];
                base/=2;
            }   
        }
        return _sum;
    }
    void flipr(int r,vector<vector<int>>& A)
    {
        for(int i=0;i<A[0].size();i++)
            A[r][i]=1-A[r][i];
    }
    void flipc(int c,vector<vector<int>>& A)
    {
        for (int i=0;i<A.size();i++)
            A[i][c]=1-A[i][c];
    }
};

總結: