Skip to content

Singhvibhanshu/fix issue 12218 #12231

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions data_structures/arrays/matrix_zero_problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
def setzeroes(matrix):
rows = len(matrix)
cols = len(matrix[0])
# To keep track if we need to zero out the first row and first column
first_row_zero = False
first_col_zero = False
# Check if the first column should be zero
for i in range(rows):
if matrix[i][0] == 0:
first_col_zero = True
# Check if the first row should be zero
for j in range(cols):
if matrix[0][j] == 0:
first_row_zero = True
# Mark zero rows and columns by using the first row and first column
for i in range(1, rows):
for j in range(1, cols):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
# Set matrix cells to zero based on marks
for i in range(1, rows):
for j in range(1, cols):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
# Zero out the first row if needed
if first_row_zero:
for j in range(cols):
matrix[0][j] = 0
# Zero out the first column if needed
if first_col_zero:
for i in range(rows):
matrix[i][0] = 0
# Example input
matrix = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
# Call the function
setzeroes(matrix)
# Print the result
for row in matrix:
print(row)