Skip to content

Instantly share code, notes, and snippets.

@humbroll
Created August 7, 2016 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humbroll/30699f00dd73317401e4b4d98f152967 to your computer and use it in GitHub Desktop.
Save humbroll/30699f00dd73317401e4b4d98f152967 to your computer and use it in GitHub Desktop.
Zero matrix
#!/usr/bin/env python
# Zero matrix
# Write an algorithm such that if an element in a MxN matrix is 0, its entire row and column are set
# to 0
import copy
class ZeroMatrix:
def __init__(self, matrix):
self.matrix = matrix
self.matrix_len = len(matrix)
def run(self):
result = copy.deepcopy(self.matrix)
zero_x_index_list = []
zero_y_index_list = []
for i, row in enumerate(self.matrix):
for j, ele in enumerate(row):
if ele == 0:
zero_x_index_list.append(i)
zero_y_index_list.append(j)
for x in range(self.matrix_len):
result[i][x] = 0
result[x][j] = 0
elif i in zero_x_index_list or j in zero_y_index_list:
continue;
else:
result[i][j] = ele
return result
def print_matrix(self, matrix):
return "\n".join([str(m) for m in matrix])
if __name__ == '__main__':
matrix = \
[
[ 1, 2, 3, 4, 0, 6, 7],
[ 1, 2, 3, 4, 5, 6, 7],
[ 1, 2, 3, 4, 5, 6, 7],
[ 1, 0, 3, 4, 5, 6, 7],
[ 1, 2, 3, 4, 0, 6, 7],
[ 1, 2, 3, 4, 5, 6, 7],
[ 1, 2, 3, 4, 5, 6, 7],
]
zero_matrix = ZeroMatrix(matrix)
result = zero_matrix.run()
print "INPUT"
print zero_matrix.print_matrix(matrix)
print "OUTPUT"
print zero_matrix.print_matrix(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment