Wednesday, May 25, 2016

Very Common Problem on Matrix,if an element in an MXN matrix is 0,its entire row and column are set to 0.

Solution:

public void setZero(int[][] matrix)
{
  boolean[] row= new boolean[matrix.length];
  boolean[] row= new boolean[matrix[0].length];

  for(int i=0;i<matrix.length;i++)
  {
    for(int j=0;j<matrix[0].length; i++)
    {
      if(matrix[i][j] == 0)
      {
         row[i]=true;
         column[j]=true;
      }
    }
  }

  for(int i=0;i<row.length;i++)
  {
   if(row[i] nullifRow(matrix,i));
  }


  for(int j=0;j<column.length;j++)
  {
   if(column[j] nullifColumn(matrix,j));
  }

  public void nullifRow(int[][]matrix , int row)
  {
    for(int j=0; j<matrix[0].length; j++)
    {
      matrix[row][j] = 0 ;
    }
  }

  public void nullifColumn(int[][]matrix , int column)
  {
    for(int i=0; i<matrix[0].length; i++)
    {
      matrix[column][i] = 0 ;
    }
  }

}

Space Complexity: o(N) we can not reduce space complexity further but we can use bit vector instead of boolean array but still it would be o(N) space.

No comments: