Saturday, October 3, 2015

[1.7] set entire row and column Zero if matrix element Zero

1. Example

1230
4567
6789

=>

0000
4560
6780


2. Implementation


public static void setZeroes(int[][] matrix)
{


 
    // validate the input
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
        return matrix;
    



    boolean rowFlag = false;
    boolean colFlag = false;




    // check 1st row
    for (int j=0 ; j < matrix[0].length; j++)
    {
        if ( matrix[0][j] == 0)
        {
           rowFlag = true;
           // NOTE: break
           break;
        }
    }

 


    // check 1st column
    for(int i =0 ; i < matrix.length; i++)
    {
         if (matrix[i][0] == 0)
         {
            colFlag = true;
            // NOTE: break
            break;
         }
    }




    // move the rest to the first column and row
    //for (int i = 0 ; i < matrix.length; i++)
    // NOTE: already check 1st col
    for ( int i =1 ; i < matrix.length ; i++)
    {
          //for (int j = 0 ; j < matrix[0].length; j++)
          for (int j = 1; j < matrix[0].length; j++)
          {
                 if (matrix[i][j] == 0 )
                 {
                        matrix[0][j] = 0;
                        matrix[i][0] = 0;
                 }
          }
    }





    // set Zeroes   
    for (int i = 0 ; i < matrix.length; i++)
    {
          for (int  j= 0; j < matrix[0].length;j++)
          {

                  if ( matrix[i][0] == 0 || matrix[0][j] == 0)
                       matrix[i][j] = 0;
          }
    }
    if (rowFlag)
    {
          for (int j =  0; j < matrix[0].length ; j++)
                 matrix[0][j] = 0;
    }
    if (colFlag)
    {
          for (int i = 0 ; i < matrix.length; i++)
                matrix[i][0] = 0;
    }





}


3. Similar ones

No comments:

Post a Comment