The task at hand is to detect zeros in a matrix and set all cells in the same row, column to zeros. E.g. given matrix with 0
[ 1 2 0]
[ 4 5 7]
[ 9 8 3]
becomes
[ 0 0 0]
[ 4 5 0]
[ 9 8 0]
I tried to solve similar problem, created helper 'mark_matrix' with all 1 and set it to zero whenever i find 0 in the original matrix.
Here is the online ide code to run it. I included lots of print statements, the logic: whenever zero found, it takes current [i,j] and starts going thru the helper mark_matrix to set the i-th row and j-th column to zeros.
class Sol:
def print_matrix(self, m):
for i in range(0, len(m)):
for j in range(0, len(m[0])):
print(m[i][j], sep=' ', end=' ')
print()
print('------')
def fill_row_column_zeros(self, m):
mark_matrix = [1]*len(m[0])
mark_matrix = [mark_matrix] * len(m)
print('before, empty mark matrix')
self.print_matrix(mark_matrix)
for i in range(len(m)):
for j in range(len(m[0])):
if m[i][j] != 0:
print('skipping [%d][%d] ' % (i, j))
elif m[i][j] == 0:
print('found zero at [%d][%d] ' % (i, j))
print('-----------------------')
row = i
column = j
for a in range(len(m)):
for b in range(len(m[0])):
print('row is %d' % row)
if a == row:
mark_matrix[a][b] = 0
print(
'changing at coords: [%d][%d]' % (row, b))
self.print_matrix(mark_matrix)
for a in range(len(m)):
for b in range(len(m[0])):
print('columns is %d' % column)
if b == column:
mark_matrix[a][b] = 0
print(
'changing at coords: [%d][%d]' % (b, column))
self.print_matrix(mark_matrix)
print('\n')
print('***** END *******')
print('mark matrix now')
self.print_matrix(mark_matrix)
if __name__ == '__main__':
s = Sol()
m = [[1, 3, 0], [4, 5, 6], [6, 8, 9]]
print('original matrix')
s.fill_row_column_zeros(m)
However it just changes the entire helper mark_matrix to zeros. I did check the indexes.
0 0 0
0 0 0
0 0 0
e.g. the zero is at [0,2] so I take all the row's indices - [0,0], [0,1],[0,2] and set to 0 Same for j=2, [0,2], [1,2],[2,2] set to 0. But the matrix becomes all 0
[ 1 2 0]
[ 4 5 7]
[ 9 8 3]