Monday, August 10, 2015

Matrix - Setting Rows/Cols To Certain Values

Problem

Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column 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;
 }


Note: This is a problem from the book "Cracking the Coding Interview: 150 Programming Questions and Solutions", which I am currently reading.

No comments:

Post a Comment