Problem
Problem page: https://leetcode.com/problems/set-matrix-zeroes/
Topics: Array
Difficulty: Medium
Similar problems: (M) Game of Life
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(m**n) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Analysis
The simplest algorithm that came to mind when I saw this problem was to make one m*n pass and, whenever I hit a 0, zero out its row and column. That could mean zeroing out the same elements over and over.
Then I thought I should keep track of which rows and columns to zero out during the pass and do all the zeroing in one go afterward. That meant I needed space to record whether each row and column needed to be zeroed out.
But the problem says I can't use extra space, so the matrix itself is the only place to keep track. If a point satisfies (x,y)=0, I mark (x,0) and (0,y) as 0 to show that column x and row y need to be zeroed out.
But if the first element of the second row is 0, (0,0) gets marked as 0. That would zero out the first row and the first column, even though the first row shouldn't be zeroed out in this case. I use two extra variables to keep track of whether the first row and the first column need to be zeroed out. I spent a long time trying to use the point (m-1,n-1) to get rid of those two extra variables. I couldn't get it to work, but I'll keep thinking about whether it's possible. Still, the problem asks for constant space, so the algorithm I have now already meets the requirement.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-set-matrix-zeroes/
