Why it works
- Clearing at once would spread: a fresh 0 would look like a zero from the start and clear more rows and columns. So the first pass only marks, and the second one clears.
- The marks need a place for every row and every column: column 0 has a cell in each row and row 0 a cell in each column, so the matrix keeps its own marks without extra memory.
- A mark written into row 0 looks the same as a zero row 0 had itself, and m[0][0] would serve both row 0 and column 0. The two flags, taken before any mark is written, tell them apart, and row 0 and column 0 are cleared last, after their marks are read.
Complexity
Time O(rows × columns): two passes over the cells, plus row 0 and column 0 twice. Memory O(1): the marks live in the matrix itself, beside two flags.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗