Advertisement
imashutosh51

Set Matrix Zeroes

Oct 16th, 2022
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. /*
  2. M-1: take two array one is of row size and other for columns size of matrix and initialise with -1.
  3.      traverse the whole matrix and if any (i,j)=0 then make row_array[i]=0 and col_array[j]=0;
  4.      Now we know which array should be 0 and which column should be 0.
  5.      Traverse the row_array and make whole row for the matrix as 0 and same for column array.
  6.      But this approach take O(m+n) size.
  7.      
  8. M-2: We will create row_array and col_array inside the matrix.
  9.      We will find the first 0 in the matrix eg (r,c) so we will use whole rth row as column array
  10.      and cth column as row array.
  11.      One catch is there,It is 100% sure that rth row and cth column will be all 0 so we will fill
  12.      that row and column at end otherwise it will create mess.
  13.      
  14.      
  15.      
  16. */
  17.  
  18. class Solution {
  19. public:
  20.     void setZeroes(vector<vector<int>>& matrix) {
  21.        int r=-1,c=-1;
  22.        for(int i=0;i<matrix.size();i++){       //finding first 0 location and deciding row_arr and col_arr
  23.            for(int j=0;j<matrix[0].size();j++){
  24.                if(matrix[i][j]==0){r=i;c=j;break;}
  25.            }
  26.        }
  27.        if(r==-1) return;
  28.        for(int i=0;i<matrix.size();i++){     //selecting rows and column to be 0
  29.            for(int j=0;j<matrix[0].size();j++){
  30.                if(i==r && j==c) continue;
  31.                if(matrix[i][j]==0){matrix[i][c]=0; matrix[r][j]=0;}
  32.            }
  33.        }
  34.        for(int i=0;i<matrix.size();i++){  //making selected columns as 0.
  35.            if(i==r) continue;
  36.            if(matrix[i][c]==0){ for(int j=0;j<matrix[0].size();j++) matrix[i][j]=0; }
  37.        }
  38.        for(int j=0;j<matrix[0].size();j++){  //making selected rows as 0.
  39.            if(j==c) continue;
  40.            if(matrix[r][j]==0){ for(int i=0;i<matrix.size();i++) matrix[i][j]=0; }
  41.        }
  42.        for(int i=0;i<matrix.size();i++){     //making whole row_arr and col_arr as 0.
  43.            for(int j=0;j<matrix[0].size();j++){
  44.                if(i==r || j==c) matrix[i][j]=0;
  45.            }
  46.        }
  47.        
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement