[LeetCode] Remove All Ones With Row and Column Flips

2128. Remove All Ones With Row and Column Flips

You are given an m x n binary matrix grid.

In one operation, you can choose any row or column and flip each value in that row or column (i.e., changing all 0’s to 1’s, and all 1’s to 0’s).

Return true if it is possible to remove all 1’s from grid using any number of operations or false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool removeOnes(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < m; i++) {
if(grid[0][i]) {
for(int j = 0; j < n; j++)
grid[j][i] = !grid[j][i];
}
}
for(int i = 1; i < n; i++) {
int sum = accumulate(grid[i].begin(), grid[i].end(), 0);
if(!(sum == m or sum == 0)) return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/13/PS/LeetCode/remove-all-ones-with-row-and-column-flips/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.