当前位置:网站首页>leetcode_ 861. Score after flipping the matrix

leetcode_ 861. Score after flipping the matrix

2020-12-16 05:20:05 Sad love flowers, unintentional people

Catalog

One 、 Topic content

Two 、 Their thinking

3、 ... and 、 Code


One 、 Topic content

There's a two-dimensional matrix  A The value of each of these elements is  0  or  1 .

Move means to select any row or column , And convert each value in the row or column : Will all 0 All changed to 1, Will all 1 All changed to 0.

After making any number of moves , Explain each line of the matrix as a binary number , The score of the matrix is the sum of these numbers .

Return as high a score as possible .

Example :

Input :[[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output :39
explain :
Convert to [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Tips :

1 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j]  yes  0 or  1

Two 、 Their thinking

Get as many numbers as you can , be The first column should all be 1, And then, except for the first column, from left to right Of each column 1 The number of should be greater than 0 The number of , Otherwise, flip , In the end, we can get the result ;

3、 ... and 、 Code

class Solution:
    def matrixScore(self, A: list) -> int:
        m = len(A)
        n = len(A[0])

        #  The first column is full of 1
        for i in range(m):
            if A[i][0] == 1:
                continue
            else:
                for j in range(n):
                    A[i][j] = 1 - A[i][j]

        for j in range(n):
            zero_count = 0
            for i in range(m):
                if A[i][j] == 0:
                    zero_count += 1
            #  A column  0  More than half of them 
            if zero_count * 2 > m:
                #  Inversion 
                for i in range(m):
                    if A[i][j] == 0:
                        A[i][j] = 1
                    else:
                        A[i][j] = 0
        res = 0
        #  Sum up 
        for i in range(m):
            tmp = 0
            for j in range(n - 1, -1, -1):
                power = n - j - 1
                tmp += pow(2, power) * A[i][j]
            res += tmp
        return res


if __name__ == '__main__':
    A = [[0,0,1,1],
         [1,0,1,0],
         [1,1,0,0]]
    s = Solution()
    ans = s.matrixScore(A)
    print(ans)

版权声明
本文为[Sad love flowers, unintentional people]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201216051942951x.html