问题描述
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: Could you devise a constant space solution?
问题分析
简单方法:设置两个长度分别为m和n的标记数组分别记录行和列是否有0,根据标记数组将某些矩阵元素置0;
常数空间方法:只能申请常数空间,但是可以利用矩阵本身的空间来记录信息!首先记录第1行和第1列是否需要置0,这里需要两个常数空间来标记,然后用第1行和第1列作为标记数组的空间,来对除第1行和第1列之外的行和列进行记录。最后根据记录将某些矩阵元素置0。
AC代码
#encoding=utf-8
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
# 注释掉的是O(mn)空间的方法
# m = len(matrix)
# if m == 0:
# return matrix
# n = len(matrix[0])
# if n == 0:
# return matrix
# flag_row = [False for i in range(m)]
# flag_column = [False for i in range(n)]
# for i in range(m):
# for j in range(n):
# if matrix[i][j] == 0:
# flag_row[i] = True
# flag_column[j] = True
# for i in range(m):
# for j in range(n):
# if flag_row[i] or flag_column[j]:
# matrix[i][j] = 0
#下面是常数空间的算法
m = len(matrix)
if m == 0:
return matrix
n = len(matrix[0])
if n == 0:
return matrix
flag_row = False
flag_column = False
#记录第1行和第1列是否置0
for i in range(n):
if matrix[0][i] == 0:
flag_row = True
break
for j in range(m):
if matrix[j][0] == 0:
flag_column = True
break
#用第1行和第1列记录其他行和列是否置0
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[0][j] = 0
matrix[i][0] = 0
#改变其他行和列的值
for i in range(1, m):
for j in range(1, n):
if matrix[0][j] == 0 or matrix[i][0] == 0:
matrix[i][j] = 0
#改变第一行和第一列的值
if flag_row:
for j in range(n):
matrix[0][j] = 0
if flag_column:
for i in range(m):
matrix[i][0] = 0