Sunday, September 2, 2012

Set matrix rows and cols to zero


Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

Approach:

  1. Iterate through the matrix, and where ever we encounter 0, remember the row and col in separate arrays.
  2. Do the second iteration through the matrix for the rows and cols stored above and mark them zero.


Sample Input/Output:
printing original matrix..
1 2 0 
4 5 6 
0 8 9 
After removing zero rows and cols: 
0 0 0 
0 5 0 
0 0 0 
printing original matrix..
4 5 6 
7 0 8 
9 1 2 
After removing zero rows and cols: 
4 0 6 
0 0 0 
9 0 2 

1 comment: