leetcode brush Series title 2019-5-15

861. The flip after scoring matrix

A has a two-dimensional matrix wherein each element is 0 or 1.

Moving means to select any row or column, and converting the value of each row or column: all changes are 0 to 1, 1 are all changed to 0.

After making any number of movement, each row of the matrix in accordance with a binary number interpreted, the score is the sum of the numbers of the matrix.

Return the highest possible score.

示例:

输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]]
输出:39
解释:
转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
 

提示:

1 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j] 是 0 或 1

Problem-solving ideas:

  • Said problem is how to invert a matrix such that each row corresponding to the maximum value,
    • In binary, for each row, the first one from the left is the highest bit, all bits of binary and back to +1, so I want each line maximum, must be equal to 1. Therefore, the first inverted for each row The first condition is that is 0, 0 is inverted, 1 is not reversed.
    • For each column, as long as this satisfies the column number is smaller than the number of zero to one, since the binary conversion result of the conversion of zero or zero, so that a better anyway. Thus the condition column is greater than half the number of zero reversal.
    • Should first lateral inversion, then vertical reverse, or need to conduct a multi-reversal process. Because no effect on the reverse of the column line inversion conditions, and conditions on the reverse line inversion influential column

We need to traverse the two horizontal and vertical flipping, flip lateral traversing that A [i] [0] == 0, the longitudinal direction is required according to the number of the current column 0, is greater than half the need to flip. code show as below:

class Solution:
    def matrixScore(self, A: List[List[int]]) -> int:
        # 先进行横向反转
        m = len(A)
        n = len(A[0])
        for i in range(m):
            if not A[i][0]:
                for j in range(n):
                    A[i][j] = (A[i][j] + 1) % 2
        # 纵向反转
        for j in range(n):
            tmp = 0
            for i in range(m):
                if not A[i][j]:
                    tmp += 1
            if tmp > (m//2):
                for i in range(m):
                    A[i][j] = (A[i][j] + 1) % 2
        res = 0
        for i in range(m):
            prop = 1
            for j in range(n)[::-1]:
                res += int(A[i][j])*prop
                prop *= 2
        return res

Guess you like

Origin blog.csdn.net/weixin_43615373/article/details/90245049
Recommended