# Minimum operations required to set all elements of binary matrix

Given a binary matrix of N rows and M columns. The operation allowed on the matrix is to choose any index (x, y) and toggle all the elements between the rectangle having top-left as (0, 0) and bottom-right as (x-1, y-1). Toggling the element means changing 1 to 0 and 0 to 1. The task is to find minimum operations required to make set all the elements of the matrix i.e make all elements as 1.

Examples:

```Input : mat[][] =  0 0 0 1 1
0 0 0 1 1
0 0 0 1 1
1 1 1 1 1
1 1 1 1 1
Output : 1
In one move, choose (3, 3) to make the
whole matrix consisting of only 1s.

Input : mat[][] =  0 0 1 1 1
0 0 0 1 1
0 0 0 1 1
1 1 1 1 1
1 1 1 1 1
Output : 3
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The idea is to start from the end point (N – 1, M – 1) and traverse the matrix in reverse order. Whenever we encounter a cell which has a value of 0, flip it.
Why traversing from end point ?
Suppose there are 0 at (x, y) and (x + 1, y + 1) cell. You shouldn’t flip a cell (x + 1, y + 1) after cell (x, y) because after you flipped (x, y) to 1, in next move to flip (x + 1, y + 1) cell, you will flip again (x, y) to 0. So there is no benefit from the first move for flipping (x, y) cell.

Below is C++ implementation of this approach:

```// C++ program to find minimum operations required
// to set all the element of binary matrix
#include <bits/stdc++.h>
#define N 5
#define M 5
using namespace std;

// Return minimum operation required to make all 1s.
int minOperation(bool arr[N][M])
{
int ans = 0;
for (int i = N - 1; i >= 0; i--)
{
for (int j = M - 1; j >= 0; j--)
{
// check if this cell equals 0
if(arr[i][j] == 0)
{
// increase the number of moves
ans++;

// flip from this cell to the start point
for (int k = 0; k <= i; k++)
{
for (int h = 0; h <= j; h++)
{
// flip the cell
if (arr[k][h] == 1)
arr[k][h] = 0;
else
arr[k][h] = 1;
}
}
}
}
}
return ans;
}

// Driven Program
int main()
{
bool mat[N][M] =
{
0, 0, 1, 1, 1,
0, 0, 0, 1, 1,
0, 0, 0, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1
};

cout << minOperation(mat) << endl;

return 0;
}
```

Output:

```3
```

Time Complexity: O(N2 * M2).
Space Complexity: O(N*M).

This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.5 Average Difficulty : 1.5/5.0
Based on 2 vote(s)