73. Set Matrix Zeroes

Given a mxn matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Solution:

Using the first row and first column value as an indicator on whether the row and column contains 0 element.

  1. check if first row and first column contains zero, mark them with two boolean identifiers
  2. traverse the matrix from the second row and column, for every element matrix[i,j] = 0, mark matrix[i,0], [0,j] = 0;
  3. for each element in matrix, check the corresponding first row and first column element to update its value
  4. update all the elements in first row and first column based on the two identifiers
  5. public class Solution {
     public void setZeroes(int[][] matrix) {
         if(matrix == null || matrix.length == 0){
             return;
         }    
         boolean firstrow = false;
         boolean firstcolumn = false;
    
         int row = matrix.length;
         int column = matrix[0].length;
    
         for(int i = 0; i < column; i++){
             if(matrix[0][i] == 0){
                 firstrow = true;
                 break;
             }
         }
    
         for(int i = 0; i < row; i++){
             if(matrix[i][0] == 0){
                 firstcolumn = true;
                 break;
             }
         }
         for(int i = 1; i < row; i++){
             for(int j = 1; j < column; j++){
                 if(matrix[i][j] == 0){
                     matrix[i][0] = 0;
                     matrix[0][j] = 0;
                 }
             }
         }
         for(int i = 1; i < row; i++){
             for(int j = 1; j < column; j++){
                 if(matrix[i][0] == 0 || matrix[0][j] == 0){
                     matrix[i][j] = 0;
                 }
             }
         }
    
         if(firstrow == true){
            for(int i = 0; i < column; i++){
                 matrix[0][i] = 0;
            }
         }
    
         if(firstcolumn == true){
            for(int j = 0; j < row; j++){
                 matrix[j][0] = 0;
            }
         }
    
         return;
     }
    }
    

results matching ""

    No results matching ""