Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:Did you use extra space? A straight forward solution using O(_m__n_) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution?
classSolution: # @param matrix, a list of lists of integers # RETURN NOTHING, MODIFY matrix IN PLACE. defsetZeroes(self, matrix): m , n = len(matrix), len(matrix[0]) temp = [[matrix[i][j] for j inrange(n)] for i inrange(m)] for i inrange(m): for j inrange(n): ifnot temp[i][j]: self.setZero(i,j,n,m,matrix) defsetZero(self,row,col,n,m,matrix): for i inrange(m): matrix[i][col]=0 for j inrange(n): matrix[row][j]=0
classSolution: # @param matrix, a list of lists of integers # RETURN NOTHING, MODIFY matrix IN PLACE. defsetZeroes(self, matrix): m , n = len(matrix), len(matrix[0]) row , col = [0for i inrange(m)] , [0for i inrange(n)] for i inrange(m): for j inrange(n): ifnot matrix[i][j]: row[i]=col[j]=1 for i inrange(m): if row[i]: for j inrange(n): matrix[i][j]=0
for j inrange(n): if col[j]: for i inrange(m): matrix[i][j]=0
classSolution(object): defsetZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """
m, n, col0_zero = len(matrix), len(matrix[0]), False for i inrange(m): ifnot matrix[i][0]: col0_zero = True for j inrange(1, n): ifnot matrix[i][j]: matrix[i][0] = matrix[0][j] = 0
for i inrange(m - 1, -1, -1): for j inrange(n - 1, 0, -1): if (not matrix[i][0]) or (not matrix[0][j]): matrix[i][j] = 0 if col0_zero: matrix[i][0] = 0