Implement an algorithm such that if an element in an mxn matrix is 0, its entire row and column are set to 0 without replicating the matrix
Answers
Answer:
public static void SetZero( int [][] matrix, int m, int n )
{
boolean[] row = new boolean[m];
boolean[] column = new boolean[n];
for( int i = 0; i < m; i++ )
{
for( int j = 0; j < n; j++ )
{
if( matrix[i][j] == 0 )
{
row[i] = true;
column[j] = true;
}
}
}
for( int i = 0; i < m; i++ )
{
if( row[i] )
{
for( int j = 0; j < n; j++ )
{
matrix[i][j] = 0;
}
}
}
for( int j = 0; j < n; i++ )
{
if( column[j] )
{
for( int i = 0; i < m; i++ )
{
matrix[i][j] = 0;
}
}
}
}