Minimum operations required to set all elements of binary matrix in C++

C++Server Side ProgrammingProgramming

Problem statement

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.

Example

If input matrix is {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}
Then answer is 1

In one move, choose (3, 3) to make the whole matrix consisting of only 1s.

Algorithm

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

Example

#include <iostream>
#define ROWS 5
#define COLS 5
using namespace std;
int getMinOperations(bool arr[ROWS][COLS]) {
   int ans = 0;
   for (int i = ROWS - 1; i >= 0; i--){
      for (int j = COLS - 1; j >= 0; j--){
         if(arr[i][j] == 0){
            ans++;
            for (int k = 0; k <= i; k++){
               for (int h = 0; h <= j; h++){
                  if (arr[k][h] == 1)
                     arr[k][h] = 0;
                  else
                     arr[k][h] = 1;
               }
            }
         }
      }
   }
   return ans;
}
int main() {
   bool mat[ROWS][COLS] = {
      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 << "Minimum required operations = " << getMinOperations(mat) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Minimum required operations = 3
raja
Published on 22-Nov-2019 11:37:09
Advertisements