Set Matrix Ones

Posted: 15 Dec, 2020
Difficulty: Easy


Try Problem

You have been given a non-empty grid ‘MAT’ consisting of only 0s and 1s. Your task is to modify it in such a way that if a cell has value 1 (MAT[i][j] == 1), then all the cells of the i-th row and j-th column should be changed to 1.

For Example
If the given grid is this:
[0, 0, 0]
[0, 0, 1]

Then the modified grid will be
[0, 0, 1],
[1, 1, 1]
Input Format
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first input line of each test case contains two space integers‘ N’ and ‘M’ representing the number of rows and columns of the grid, respectively.

The next 'N' lines represent the rows of the grid. Every row contains M single space-separated integers.
Output Format
For each test case, print the modified grid.

Print the output of each test case in a separate line.
You are not required to print the expected output; it has already been taken care of. Just implement the function. 

Also, update the given matrix in place.
1 <= T <= 100
1 <= N <= 50
1 <= M <= 50
0 <= MAT[i][j] <= 1

Time limit: 1 sec
Approach 1

We will traverse the whole grid and whenever MAT[i][j] == 1, we will mark all 0s in the i-th row and j-th column as -1. This will help us in differentiating between the 1s that are initially there in the matrix and the 1s which we will set now.


Now, traverse the grid again and mark the cells with value -1 as 1.

Try Problem