Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- M-1: take two array one is of row size and other for columns size of matrix and initialise with -1.
- traverse the whole matrix and if any (i,j)=0 then make row_array[i]=0 and col_array[j]=0;
- Now we know which array should be 0 and which column should be 0.
- Traverse the row_array and make whole row for the matrix as 0 and same for column array.
- But this approach take O(m+n) size.
- M-2: We will create row_array and col_array inside the matrix.
- We will find the first 0 in the matrix eg (r,c) so we will use whole rth row as column array
- and cth column as row array.
- One catch is there,It is 100% sure that rth row and cth column will be all 0 so we will fill
- that row and column at end otherwise it will create mess.
- */
- class Solution {
- public:
- void setZeroes(vector<vector<int>>& matrix) {
- int r=-1,c=-1;
- for(int i=0;i<matrix.size();i++){ //finding first 0 location and deciding row_arr and col_arr
- for(int j=0;j<matrix[0].size();j++){
- if(matrix[i][j]==0){r=i;c=j;break;}
- }
- }
- if(r==-1) return;
- for(int i=0;i<matrix.size();i++){ //selecting rows and column to be 0
- for(int j=0;j<matrix[0].size();j++){
- if(i==r && j==c) continue;
- if(matrix[i][j]==0){matrix[i][c]=0; matrix[r][j]=0;}
- }
- }
- for(int i=0;i<matrix.size();i++){ //making selected columns as 0.
- if(i==r) continue;
- if(matrix[i][c]==0){ for(int j=0;j<matrix[0].size();j++) matrix[i][j]=0; }
- }
- for(int j=0;j<matrix[0].size();j++){ //making selected rows as 0.
- if(j==c) continue;
- if(matrix[r][j]==0){ for(int i=0;i<matrix.size();i++) matrix[i][j]=0; }
- }
- for(int i=0;i<matrix.size();i++){ //making whole row_arr and col_arr as 0.
- for(int j=0;j<matrix[0].size();j++){
- if(i==r || j==c) matrix[i][j]=0;
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement