C++ Boolean Matrix

C++Server Side ProgrammingProgramming

Boolean matrix is a matrix that has only two elements 0 and 1. For this boolean Matrix question, we have a boolean matrix arr[m][n] of size mXn. And the condition to solve is, if m[i][j] = 1 then m[i] = 1 and m[j] = 1 which means all elements of the ith row and jth column will become 1.

Let’s take an example,

Input: arr[2][2] = 1 0
                   0 0
Output: arr[2][2] = 1 1
                    1 0

Explanation− arr[0][0] = 1 which means arr[0][0]=arr[0][1]=1 & arr[0][0]=arr[1][0]=1.

Here, we will take two flag variables and check if the rows and columns need to be changed to one of not. If yes flag = 1 otherwise 0. And then based on this flag value we will change the values of the elements of the rows and columns. We will do the same procedure for all the elements of the array.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int R = 3;
#define C 4
void matrixflip(int mat[R][C]) {
   int row_flag = 0;
   int col_flag = 0;
   for (int i = 0; i < R; i++) {
      for (int j = 0; j < C; j++) {
         if (i == 0 && mat[i][j] == 1)
            row_flag = 1;
         if (j == 0 && mat[i][j] == 1)
            col_flag = 1;
         if (mat[i][j] == 1) {
            mat[0][j] = 1;
            mat[i][0] = 1;
         }
      }
   }
   for (int i = 1; i < R; i++) {
      for (int j = 1; j < C; j++) {
         if (mat[0][j] == 1 || mat[i][0] == 1) {
            mat[i][j] = 1;
         }
      }
   }
   if (row_flag) {
      for (int i = 0; i < C; i++) {
         mat[0][i] = 1;
      }
   }
   if (col_flag) {
      for (int i = 0; i < R; i++) {
         mat[i][0] = 1;
      }
   }
}
int main() {
   int mat[R][C] = { { 1, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } };
   cout << "Input Matrix :\n";
   for (int i = 0; i < R; i++) {
      for (int j = 0; j < C; j++) {
         cout << mat[i][j]<<" ";
      }
      cout <<endl;
   }
   matrixflip(mat);
   cout << "Matrix after bit flip :\n";
   for (int i = 0; i < R; i++) {
      for (int j = 0; j < C; j++) {
         cout << mat[i][j]<<" ";
      }
      cout <<endl;
   }
   return 0;
}

Output

Input Martix:
1 0 0 0
0 0 0 0
0 0 1 0
Matirx after bit flip :
1 1 1 1
1 0 1 0
1 1 1 1
raja
Published on 07-Oct-2019 11:40:22
Advertisements