您的位置:首页 > 其它

leetcode Set Matrix Zeroes

2015-11-16 16:14 323 查看

Question

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Solution

If you have to store some thing, but the problem requires in place solution, you may consider storing it in the array given.

class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if matrix == None or len(matrix) == 0:
return
first_col = False
first_row = False
for i in xrange(len(matrix[0])):
if matrix[0][i] == 0:
first_row = True
break;
for i in xrange(len(matrix)):
if matrix[i][0] == 0:
first_col = True
break;
for i in xrange(1,len(matrix)):
for j in xrange(1,len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in xrange(1,len(matrix)):
for j in xrange(1,len(matrix[0])):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if first_row:
for i in xrange(len(matrix[0])):
matrix[0][i] = 0
if first_col:
for i in xrange(len(matrix)):
matrix[i][0] = 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: