If an element of an m × n matrix is 0, set its entire row and column to 0. Do it in place.
Use row 0 and column 0 as the marker sets. Remember separately whether row 0 and column 0 themselves contained a zero, and clear them last.
1function setZeroes(matrix: number[][]): void {2const m = matrix.length, n = matrix[0].length;3const row0 = matrix[0].includes(0), col0 = matrix.some((row) => row[0] === 0);4for (let r = 1; r < m; r++)5for (let c = 1; c < n; c++)6if (matrix[r][c] === 0) matrix[r][0] = matrix[0][c] = 0;7for (let r = 1; r < m; r++)8for (let c = 1; c < n; c++)9if (matrix[r][0] === 0 || matrix[0][c] === 0) matrix[r][c] = 0;10if (row0) for (let c = 0; c < n; c++) matrix[0][c] = 0;11if (col0) for (let r = 0; r < m; r++) matrix[r][0] = 0;12}
| 0 | 1 | 2 | 0 |
| 3 | 4 | 5 | 2 |
| 1 | 3 | 1 | 5 |
Does row 0 have a zero? true. Does column 0? true.
Space: play/pause · ←/→: step