Problem link:click
This is very easy problem. In this problem you have to make all elements of a row or a column to zero if any element of the matrix of the specific row or column is zero. For this purpose we can take the first row and the first column as a flag of the row and column. If any element of a row or column is zero we will make the flag of first row and columns as zero.
For making all elements of the row and column zero we just have to check if matrix[i][0]==0 or matrix[0][j]==0.
Code:
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int col=matrix[0].size(),row=matrix.size(),col0=1; for(int i=0;i<row;i++){ if(matrix[i][0]==0)col0=0; for(int j=1;j<col;j++){ if(matrix[i][j]==0){ matrix[0][j]=0; matrix[i][0]=0; } } } for(int i=row-1;i>=0;i--){ for(int j=col-1;j>=1;j--){ if(matrix[i][0]==0 || matrix[0][j]==0){ matrix[i][j]=0; } } if(col0==0)matrix[i][0]=0; } } };
No comments:
Post a Comment
If you have any doubts, let me know through comments