Topics are as follows:
Given a
matrix
consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.Return the maximum number of rows that have all values equal after some number of flips.
Example 1:
Input: [[0,1],[1,1]] Output: 1 Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: [[0,1],[1,0]] Output: 2 Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
Input: [[0,0,0],[0,0,1],[1,1,0]] Output: 2 Explanation: After flipping values in the first two columns, the last two rows have equal values.
Note:
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
- All
matrix[i].length
's are equalmatrix[i][j]
is0
or1
Outline of Solution: all the elements in any row of the matrix makes up a string, e.g. 0,010,110, this line should become all 0 or all 1, then to row conversion after 3 or 4 times. After transformation, it is clear that the matrix string 0,010,110 or 1,101,001 last row will become all 0 or all 1. Thus the subject becomes a row in the identify matrix, and the matrix such that the entire row or equal line up opposite rows (i.e., rows corresponding to 1,1 0 corresponding to 0). How to obtain the maximum value it? Disjoint-set perfectly suited to the scene.
code show as below:
class Solution(object): def maxEqualRowsAfterFlips(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ parent = [i for i in range(len(matrix))] def find(v1): p1 = parent[v1] if p1 != v1: return find(p1) return p1 def union(v1,v2): p1 = find(v1) p2 = find(v2) if p1 <= p2: parent[v2] = p1 else: parent[v1] = p2 def toString(l1): new_l1 = map(lambda x: str(x), l1) return ''.join(new_l1) row = [] row_inverse = [] for i in range(len(matrix)): row.append(toString(matrix[i])) v1_inverse = '' for k in row[i]: v1_inverse += '0' if k == '1' else '1' row_inverse.append(v1_inverse) for i in range(len(matrix)): v1 = row[i] v1_inverse = row_inverse[i] for j in range(i+1,len(matrix)): v2 = row[j] if v1 == v2 or v1_inverse == v2: union(i,j) December = {} res = 0 for i in range(len(matrix)): p = find(i) dic[p] = dic.setdefault(p,0) + 1 res = max(res,dic[p]) return res