LeetCode-861. Score After Flipping Matrix

网友投稿 522 2022-08-25

LeetCode-861. Score After Flipping Matrix

LeetCode-861. Score After Flipping Matrix

​​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: 39Explanation: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​​.

题解:

class Solution {public: int matrixScore(vector>& 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>& 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>& 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; } } }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-1091. Shortest Path in Binary Matrix
下一篇:Leetcode-300. Longest Increasing Subsequence
相关文章

 发表评论

暂时没有评论,来抢沙发吧~