Skip to content

Instantly share code, notes, and snippets.

@iamprayush
Created August 21, 2020 06:10
Show Gist options
  • Save iamprayush/f5f1e54120853c7afacd07003284aced to your computer and use it in GitHub Desktop.
Save iamprayush/f5f1e54120853c7afacd07003284aced to your computer and use it in GitHub Desktop.
Matrix zeros
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n, m = len(matrix), len(matrix[0])
change_row_0 = 0 in matrix[0]
change_col_0 = False
for i in range(n):
if matrix[i][0] == 0:
change_col_0 = True
break
for i in range(1, n):
for j in range(1, m):
if matrix[i][j] == 0:
matrix[0][j] = 0
matrix[i][0] = 0
for i in range(1, n):
if matrix[i][0] == 0:
for j in range(1, m):
matrix[i][j] = 0
for j in range(1, m):
if matrix[0][j] == 0:
for i in range(1, n):
matrix[i][j] = 0
if change_row_0:
for j in range(m):
matrix[0][j] = 0
if change_col_0:
for i in range(n):
matrix[i][0] = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment