Set Matrix Zeroes Cont…

Monisha Mathew
1 min readMay 2, 2019

--

Question: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

Input: 
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]

You may view the full question here.

Approach 3: After some digging, found a brilliant article. After a few iterations, this is what we have —

//Approach 3:
//Runtime: 1ms
//Memory usage: 44.8MB
class Solution {
public void setZeroes(int[][] matrix) {
//Check if First Column should be set to Zero
boolean setColZero = false;
for(int r = 0; r<matrix.length; r++){
if(matrix[r][0] == 0){
setColZero = true;
break;
}
}

//Check if First Row should be set to Zero
boolean setRowZero = false;
for(int c = 0; c<matrix[0].length; c++){
if(matrix[0][c] == 0){
setRowZero = true;
break;
}
}

//Check
for(int r = 1; r<matrix.length; r++){
for(int c = 1; c<matrix[0].length; c++){
if(matrix[r][c]==0){
matrix[r][0] = 0;
matrix[0][c] = 0;
}
}
}

//Set zeroes
for(int r = 1; r<matrix.length; r++){
for(int c = 1; c<matrix[0].length; c++){
if(matrix[r][0]==0 || matrix[0][c]==0){
matrix[r][c] = 0;
}
}
}

//Set First column zero
if(setColZero){
for(int r = 0; r<matrix.length; r++){
matrix[r][0] = 0;
}
}
//set First row zero
if(setRowZero){
for(int c = 0; c<matrix[0].length; c++){
matrix[0][c] = 0;
}
}
}
}

Find more posts here.

Cheers & Chao!

--

--