73. Set Matrix Zeroes
Given a m ✕ n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow-Up:
Could you devise a constant space solution?
Solution:
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix:
return
rows = len(matrix)
cols = len(matrix[0])
col0 = 1
for i in xrange(rows):
if matrix[i][0] == 0:
col0 = 0
for j in xrange(1, cols):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in xrange(rows - 1, -1, -1):
for j in xrange(cols - 1, 0, -1):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if col0 == 0:
matrix[i][0] = 0
Lessons:
- Use first row to save each column's state.
- Use first column to save each row's state.
- Use a variable to save first column's state.