​https://leetcode.com/problems/score-after-flipping-matrix/description/​

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. ​1 <= A.length <= 20​
  2. ​1 <= A[0].length <= 20​
  3. ​A[i][j]​​​ is​​0​​​ or​​1​​.

题解:

class Solution {
public:
int matrixScore(vector<vector<int>>& A) {
if (A.size() == 1){
return 1;
}
int ans = 0;
int row = A.size();
int col = A[0].size();
//cout << A.size() << A[0].size();
for (int i = 0; i < row; i++){
if (A[i][0] == 0){
changeRow(A, i);
}
}
for (int i = 1; i < col; i++){
int one = 0, zero = 0;
for (int j = 0; j < row; j++){
if (A[j][i] == 0){
zero++;
}
else {
one++;
}
}
if (one < zero){
changeColumn(A, i);
}
}
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
ans += A[i][j] * pow(2, col - 1 - j);
}
}
return ans;
}
void changeRow(vector<vector<int>>& A, int x){
for (int i = 0; i < A[x].size(); i++){
if (A[x][i] == 0){
A[x][i] = 1;
}
else{
A[x][i] = 0;
}
}
}
void changeColumn(vector<vector<int>>& A, int x){
for (int i = 0; i < A.size(); i++){
if (A[i][x] == 0){
A[i][x] = 1;
}
else{
A[i][x] = 0;
}
}
}
};