Problem
Write an algorithm such that if an element in an MxN matrix is 0, its entire row andcolumn are set to 0.
Solution
private int[][] replaceRowCol0(int[][] matrix)
{
boolean[] rowsToSetZero = new boolean[matrix.length];
boolean[] colsToSetZero = new boolean[matrix[0].length];
int i,j;
for(i = 0; i < matrix.length; i++)
{
for(j=0; j< matrix[i].length; j++)
{
if(matrix[i][j] == 0)
{
rowsToSetZero[i] = true;
colsToSetZero[j] = true;
}
}
}
for(i=0; i< rowsToSetZero.length; i++)
{
for(j=0; j< colsToSetZero.length; j++)
{
if(rowsToSetZero[i] || colsToSetZero[j])
{
matrix[i][j] = 0;
}
}
}
return matrix;
}
No comments:
Post a Comment