Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Tuesday, 30 June 2020

Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1.

Boolean Matrix Problem
Boolean Matrix Problem

Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1.

Example:
Input:
3
2 2
1 0
0 0
2 3
0 0 0 
0 0 1
4 3
1 0 0
1 0 0
1 0 0
0 0 0

Output:
1 1
1 0
0 0 1 
1 1 1
1 1 1
1 1 1
1 0 0

Here is a simple and easy solution using queue and hashing.

#include <bits/stdc++.h>

using namespace std;

int main() {
    //code
    int t;
    cin >> t;
    while (t--) {
        int n, m;
        cin >> n >> m;

        int a[n][m];
        int b[n], c[m];

        memset(b, 0, sizeof(b));
        memset(c, 0, sizeof(c));

        queue < int > ql, qr;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                cin >> a[i][j];

                if (a[i][j] == 1) {
                    if (b[i] == 0) {
                        qr.push(i);
                        b[i] = 1; 
//for eleminating duplicate col number 
                    }

                    if (c[j] == 0) {
                        ql.push(j);
                        c[j] = 1;
 //for eleminating duplicate col number 
                    }
                }

            }

        }

        while (!ql.empty()) {
            int i = ql.front();
            // cout<<i<<" ";
            ql.pop();

            for (int k = 0; k < n; ++k) {
                if (a[k][i] != 1)
                    a[k][i] = 1;
            }

        }

        // cout<<endl;

        while (!qr.empty()) {
            int i = qr.front();
            qr.pop();
            //cout<<i<<" ";
            for (int k = 0; k < m; ++k) {
                if (a[i][k] != 1)
                    a[i][k] = 1;
            }

        }
        // cout<<endl;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                cout << a[i][j] << " ";
            }
            cout << endl;
        }

    }
    return 0;
}