question
Given a NxN matrix filled with 0s and 1s, set every row that contains a 0 to all 0's and every column that contains a 0 to all 0's. Optimize for space and passes.
ex.
0 1 0 1 0
1 1 1 1 1
1 1 1 1 1
0 1 1 1 0
0 1 0 1 0
Results in
0 0 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 0 0
0 0 0 0 0
ex.
0 1 0 1 0
1 1 1 1 1
1 1 1 1 1
0 1 1 1 0
0 1 0 1 0
Results in
0 0 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 0 0
0 0 0 0 0
Use the first row/col to keep track contents of the matrix.
For this solution we'll use the first row and first columm to keep track of the rows/cols with all 1's. Also we'll keep two variables 'r' and 'c' to determine if the first row/col are all 1's.
1. Assign r and c equal to 1
2. Iterate through the first row/col doing a binary AND operation on each digit with r and c respectively (ex.
3. Iterate through the matrix setting the beginning of the row/col to 0 if a 0 is found and reset to rest of matrix to all 0's.
ex.
4. Iterate through matrix and if the first row/col are equal to 1 then set
5. Set entire first row/col equal to 0/1 based on variables r & c
Thoughts or alternate solution? Let us know in the comments below!
1. Assign r and c equal to 1
2. Iterate through the first row/col doing a binary AND operation on each digit with r and c respectively (ex.
r &= matrix[0][j]
). The result will be equal to 1 if the row/col is all 1's or 0 if there is a 0.
3. Iterate through the matrix setting the beginning of the row/col to 0 if a 0 is found and reset to rest of matrix to all 0's.
ex.
if matrix[i][j] == 0
matrix[0][j] = 0;
matrix[i][0] = 0;
else
matrix[i][j] = 0;
4. Iterate through matrix and if the first row/col are equal to 1 then set
matrix[i][j] = 1
.
5. Set entire first row/col equal to 0/1 based on variables r & c
Thoughts or alternate solution? Let us know in the comments below!