785. Remove All Ones With Row and Column Flips II

You are given a 0-indexed m x n binary matrix grid. In one operation, you can choose any i and j that meet the following conditions:

  • 0 <= i < m
  • 0 <= j < n
  • grid[i][j] == 1

and change the values of all cells in row i and column j to zero.

Return the minimum number of operations needed to remove all 1's from grid.

Example 1:

Input: grid = [[1,1,1],[1,1,1],[0,1,0]]

Output: 2

Explanation:

In the first operation, change all cell values of row 1 and column 1 to zero.

In the second operation, change all cell values of row 0 and column 0 to zero.

Example 2:

Input: grid = [[0,1,0],[1,0,1],[0,1,0]]

Output: 2

Explanation:

In the first operation, change all cell values of row 1 and column 0 to zero.

In the second operation, change all cell values of row 2 and column 1 to zero.

Note that we cannot perform an operation using row 1 and column 1 because grid[1][1] != 1.

Now Your Turn!

Pick the correct output for the given input

Consider the following grid = [[1,0,1], [0,1,0], [1,0,1]]. What is the minimum number of operations needed to remove all 1's from the grid?

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 15
  • 1 <= m * n <= 15
  • grid[i][j] is either 0 or 1.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int removeOnes(vector<vector<int>>& grid) {
// Your code goes here
}
};
Test Case

Input:

Grid