![]() |
VOOZH | about |
Given a boolean matrix mat where each cell contains either 0 or 1, the task is to modify it such that if a matrix cell matrix[i][j] is 1 then all the cells in its ith row and jth column will become 1.
Examples:
Input: [[1, 0],
[0, 0]]
Output: [[1, 1],
[1, 0]]Input: [[1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0]]
Output: [[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 0, 1, 1]]
Assuming all the elements in the matrix are non-negative. Traverse through the matrix and if you find an element with value 1, then change all the zeros in its row and column to -1. The reason for not changing other elements to 1, but -1, is because that might affect other columns and rows.
Now traverse through the matrix again and if an element is -1 change it to 1, which will be the answer.
1 1 1 1 1 1 1 1 1 0 1 1
Time Complexity: O((n * m)*(n + m)) where n is number of rows and m is number of columns in given matrix.
O(n * m) for traversing through each element and (n+m) for traversing to row and column of matrix elements having value 1.
Space Complexity: O(1)
The idea is to use two temporary arrays,
rowMarker[]and colMarker[], to keep track of which rows and columns need to be updated.
Following are the steps for this approach
1 1 1 1 1 1 1 1 1 0 1 1
Time Complexity: O(n * m) where n is number of rows and m is number of columns in given matrix.
Auxiliary Space: O(n + m) as we are taking two arrays one of size m and another of size n.
Instead of taking two dummy arrays we can use the first row and first column of the matrix for the same work. This will help to reduce the space complexity of the problem. While traversing for the second time, the first row and column will be computed first, which will affect the values of further elements. So we traverse in the reverse direction.
Since matrix[0][0] are overlapping in first row and first column. Therefore take separate variable col0 (say) to check if the 0th column has 1 or not and use matrix[0][0] to check if the 0th row has 1 or not. Now traverse from the last element to the first element and check if matrix[i][0]==1 || matrix[0][j]==1 and if true set matrix[i][j]=1, else continue.
1 1 1 1 1 1 1 1 1 0 1 1
Time Complexity: O(n * m) where n is number of rows and m is number of columns in given matrix.
Auxiliary Space: O(1)