As the first step, look for a 0 in the grid. If we can't find one, we're done.
If we found one, we know that we're supposed to nullify all 1's in the 0's row and column.
So, since we know the final value of all those cells, we could use that row and column as temporary boolean flags for whether the same row or column contains any 0's.
The exact process:
- Look through the matrix to find a 0.
- Keeping track of the coordinates of the found 0.
- Looping over each row and column, checking whether that row or column contains a 0, and setting the flag appropriately.
- Then looping over the matrix again and, for each 1 not in the flag row or column, checking whether either the row or the column flag is set, and, if it is, set that 1 to 0.
- Then setting all cells in the row and column acting as flags to 0.
This runs in linear time (O(mn) with m rows and n columns) and O(1) space.
Example:
Input:
1 1 0 1 0
1 1 1 0 1
1 0 1 1 1
1 1 1 1 1
1 1 1 1 1
Then we look for a zero, and let's say we find the top-middle one.
Then we use the top row and middle column as flag for whether the same row / column contains a 0:
0 1 0 1 1
1
1
0
0
Then we loop over the other cells setting the 1's to 0's if the flag row / column is set:
0 0 0 0
0 0 0 0
1 0 0 0
1 0 0 0
Then we set the flag row and column to 0's:
0 0 0 0 0
0
0
0
0
Then we have our final output:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
1 0 0 0 0
This would obviously be done in-place, I just separated it out visually for clarity.