博客域名:
http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/set-matrix-zeroes/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/37338299
原题页面: https://oj.leetcode.com/problems/set-matrix-zeroes/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/37338299
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(mn) 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?
class Solution:
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
if None == matrix or [ ] == matrix or None == matrix[0] or [ ] == matrix[0]:
return
firstrow_clear = False ###
firstcol_clear = False
len_x = len(matrix)
len_y = len(matrix[0])
for i in range(0, len_x):
for j in range(0, len_y):
if 0 == matrix[i][j]:
matrix[i][0] = 0
matrix[0][j] = 0
if 0 == i:
firstrow_clear = True
if 0 == j:
firstcol_clear = True
for i in range(1, len_x):
if 0 == matrix[i][0]:
for j in range(0, len_y):
matrix[i][j] = 0
for j in range(1, len_y):
if 0 == matrix[0][j]:
for i in range(0, len_x):
matrix[i][j] = 0
if firstcol_clear:
for i in range(1, len_x):
matrix[i][0] = 0
if firstrow_clear:
for j in range(1, len_y):
matrix[0][j] = 0