A Boolean Matrix - Solution

CoderIndeed
0

Problem: A Boolean Matrix

You are given a matrix Mat of m rows and n columns. The matrix is boolean so the elements of the matrix can only be either 0 or 1.
Now, if any row of the matrix contains a 1, then you need to fill that whole row with 1. After doing the mentioned operation, you need to print the modified matrix.
A Boolean Matrix Problem Contest

Hint

Input:
The first line of input contains T denoting the number of testcases. T testcases follow.
The first line of each testcase contains m and n denoting number of rows and number of columns.
Then next m lines contain n elements denoting the elements of the matrix.

Output:
For each testcase, in a new line, print the modified matrix.

Constraints:
1 <= T <= 100
1 <= m, n <= 900
Matij ∈ {0,1}

Examples:
Input:
2
5 4
1 0 0 0
0 0 0 0
0 1 0 0
0 0 0 0
0 0 0 1
1 2
0 0
Output:
1 1 1 1
0 0 0 0
1 1 1 1
0 0 0 0
1 1 1 1
0 0

Explanation:
Testcase1: rows = 5 and columns = 4
The given matrix is
1 0 0 0
0 0 0 0
0 1 0 0
0 0 0 0
0 0 0 1
Evidently, the first row contains a 1 so fill the whole row with 1. The third row also contains a 1 so that row will be filled too. Finally, the last row contains a 1 and therefore it needs to be filled with 1 too.
The final matrix is
1 1 1 1
0 0 0 0
1 1 1 1
0 0 0 0
1 1 1 1

Solution:

 #include <bits/stdc++.h>
using namespace std;

int main() {
    int T;
    cin>>T;
    
    while(T--){
        int M,N,temp;
        int i,j;
        cin>>M>>N;
        
       int mat[M][N];
        
        for(i=0; i<M; i++){
            for(j=0; j<N; j++){
                cin>>temp;
                mat[i][j] = temp;
            }
        }
        
        for(int i=0; i<M; i++){
            for(int j = 0; j<N; j++){
                if(mat[i][j]){
                    mat[i][0] = 1;
                    break;
                }
            }
        }
        
        
       for (i = 0; i < M; i++) {
        for (j = 0; j < N; j++) {
                if (mat[i][0] == 1) {
                    mat[i][j] = 1;
                }else{
                    break;
                }
            }
        }
        
        
        for(int i=0; i<M; i++){
            for(int j=0; j<N; j++){
                cout<<mat[i][j]<<" ";
            }
            cout<<endl;
        }
    }
    return 0;
}
 
 
 

 

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !