# leetcode讲解--861. Score After Flipping Matrix

liuqinh2s

## 题目

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 `0`s to `1`s, and all `1`s to `0`s.

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`.

## Java代码

``````class Solution {
public int matrixScore(int[][] A) {
for(int i=0;i<A.length;i++){
if(A[i][0]!=1){
flip(A[i]);
}
}
for(int i=0;i<A[0].length;i++){
dealColumn(A, i);
}

int result=0;
for(int i=0;i<A.length;i++){
int column=0;
for(int j=0;j<A[0].length;j++){
System.out.print(A[i][j]);
column <<= 1;
if(A[i][j]==1){
column += A[i][j];
}
}
System.out.println("\n");
result += column;
}
return result;
}

private void flip(int[] A){
for(int i=0;i<A.length;i++){
if(A[i]==0){
A[i] = 1;
}else{
A[i] = 0;
}
}
}

private void flipColumn(int[][] A, int columnNum){
for(int i=0;i<A.length;i++){
if(A[i][columnNum]==0){
A[i][columnNum]=1;
}else{
A[i][columnNum]=0;
}
}
}

private void dealColumn(int[][] A, int columnNum){
int count=0;
for(int i=0;i<A.length;i++){
if(A[i][columnNum]==0){
count++;
}
}
if(count>A.length/2){
flipColumn(A, columnNum);
}
}
}``````

42 声望
13 粉丝
0 条评论