classSolution{public:voidsetZeroes(vector<vector<int>>&matrix){constintm=matrix.size();constintn=matrix[0].size();boolshouldFillFirstRow=false;boolshouldFillFirstCol=false;for(intj=0;j<n;++j)if(matrix[0][j]==0){shouldFillFirstRow=true;break;}for(inti=0;i<m;++i)if(matrix[i][0]==0){shouldFillFirstCol=true;break;}// Store the information in the 1st row/colfor(inti=1;i<m;++i)for(intj=1;j<n;++j)if(matrix[i][j]==0){matrix[i][0]=0;matrix[0][j]=0;}// Fill 0s for the matrix except the 1st row/colfor(inti=1;i<m;++i)for(intj=1;j<n;++j)if(matrix[i][0]==0||matrix[0][j]==0)matrix[i][j]=0;// Fill 0s for the 1st row if neededif(shouldFillFirstRow)for(intj=0;j<n;++j)matrix[0][j]=0;// Fill 0s for the 1st col if neededif(shouldFillFirstCol)for(inti=0;i<m;++i)matrix[i][0]=0;}};
classSolution{publicvoidsetZeroes(int[][]matrix){finalintm=matrix.length;finalintn=matrix[0].length;booleanshouldFillFirstRow=false;booleanshouldFillFirstCol=false;for(intj=0;j<n;++j)if(matrix[0][j]==0){shouldFillFirstRow=true;break;}for(inti=0;i<m;++i)if(matrix[i][0]==0){shouldFillFirstCol=true;break;}// Store the information in the 1st row/colfor(inti=1;i<m;++i)for(intj=1;j<n;++j)if(matrix[i][j]==0){matrix[i][0]=0;matrix[0][j]=0;}// Fill 0s for the matrix except the 1st row/colfor(inti=1;i<m;++i)for(intj=1;j<n;++j)if(matrix[i][0]==0||matrix[0][j]==0)matrix[i][j]=0;// Fill 0s for the 1st row if neededif(shouldFillFirstRow)for(intj=0;j<n;++j)matrix[0][j]=0;// Fill 0s for the 1st col if neededif(shouldFillFirstCol)for(inti=0;i<m;++i)matrix[i][0]=0;}}
classSolution:defsetZeroes(self,matrix:List[List[int]])->None:m=len(matrix)n=len(matrix[0])shouldFillFirstRow=0inmatrix[0]shouldFillFirstCol=0inlist(zip(*matrix))[0]# Store the information in the 1st row/colforiinrange(1,m):forjinrange(1,n):ifmatrix[i][j]==0:matrix[i][0]=0matrix[0][j]=0# Fill 0s for the matrix except the 1st row/colforiinrange(1,m):forjinrange(1,n):ifmatrix[i][0]==0ormatrix[0][j]==0:matrix[i][j]=0# Fill 0s for the 1st row if neededifshouldFillFirstRow:matrix[0]=[0]*n# Fill 0s for the 1st col if neededifshouldFillFirstCol:forrowinmatrix:row[0]=0