Pattern visualizer
Set Matrix Zeroes
Zeroing cells while you're still scanning for zeros is a trap — a zero you just wrote would look like an original zero and cascade into rows/columns that shouldn't be touched. So split it into two passes: first scan and just remember which rows and columns contain a zero, then a second pass actually writes the zeros using that record. Animated on: matrix = [[1,1,1],[1,0,1],[1,1,1]] — if a cell is 0, zero its entire row and column (shown flattened row-major, index = row*3+col; the single 0 is at idx4, row1 col1)..
Record first, zero second
First pass: scan for zeros, remembering which rows/cols they're in — without zeroing yet, to avoid cascading.
1FUNCTION setZeroes(matrix):2 make an empty set of zero-rows and an empty set of zero-cols3 FOR each cell (r,c):4 IF matrix[r][c] is 0: add r to zero-rows and add c to zero-cols5 FOR each cell (r,c):6 IF r is in zero-rows or c is in zero-cols: set matrix[r][c] = 0
← / → step · space play · Home restart