Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Java:
public class Solution {
public void setZeroes(int[][] matrix) {
int row = matrix.length;
if(row == 0) return;
int col = matrix[0].length;
if(col == 0) return;
int i=0;
boolean rowzero = false;
boolean colzero = false;
while(i<col)
{
if(matrix[0][i] == 0)
{
rowzero = true;
break;
}
i++;
}
i=0;
while(i<row)
{
if(matrix[i][0] == 0)
{
colzero = true;
break;
}
i++;
}
for(int j=1; j<row; j++)
{
for(int k=1; k<col;k++)
{
if(matrix[j][k] == 0)
{
matrix[j][0] = 0;
matrix[0][k] = 0;
}
}
}
for(int m=1; m<row; m++)
{
for(int n=1; n<col; n++)
{
if(matrix[0][n] == 0 || matrix[m][0]==0)
{
matrix[m][n] = 0;
}
}
}
i=0;
if(rowzero)
{
while(i<col)
{
matrix[0][i] = 0;
i++;
}
}
i=0;
if(colzero)
{
while(i<row)
{
matrix[i][0] = 0;
i++;
}
}
}
}