-
Medium
-
Given an
m x n
integer matrixmatrix
, if an element is0
, set its entire row and column to0
's, and return the matrix.You must do it in place.
The most simple and naive idea is to go through the matrix searching for 0. When we find one, we change the numbers in that row and column to be "a"(so that it would not be confused with other 0s). Eventually we come back and change all the "a"s back into zero.
This method actually works out pretty well.
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m=len(matrix)
n=len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j]==0:
for k in range(m):
if matrix[k][j]!=0:
matrix[k][j]="a"
for l in range(n):
if matrix[i][l]!=0:
matrix[i][l]="a"
for i in range(m):
for j in range(n):
if matrix[i][j]=="a":
matrix[i][j]=0