Description:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Answer:
1.in-place no extra space:
My idea is simple: store states of each row in the first of that row, and store states of each column in the first of that column. Because the state of row0 and the state of column0 would occupy the same cell, I let it be the state of row0, and use another variable “col0” for column0. In the first phase, use matrix elements to set states in a top-down way. In the second phase, use states to set matrix elements in a bottom-up way.
public void setZeroes(int[][] matrix) {
int col0 = 1, rows = matrix.length, cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
2.use O(n) extra space:
public void setZeroes(int[][] matrix) {
Set<Integer> rows = new <Integer>HashSet();
Set<Integer> cols = new <Integer>HashSet();
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][j] == 0){
if(!rows.contains(i))
rows.add(i);
if(!cols.contains(j))
cols.add(j);
}
}
}
for(Integer row: rows){
for(int j = 0; j < matrix[0].length; j++ )
matrix[row][j] = 0;
}
for(Integer col: cols){
for(int i = 0; i < matrix.length; i++ )
matrix[i][col] = 0;
}
}