Set Matrix Zeroes

HardAcc. 84.6%
+40 XP 20

The Shadow Marking (Matrix Zeroes)

Imagine a "Shadow Rule": if any room in a grid contains a zero, the entire row and column for that room must be "shadowed" (set to zero). The real challenge is doing this without creating a full copy of the grid. By using the first row and column as a status board, we can mark the shadows in-place!

The Assignment

Your mission is to shadow the grid. Your function receives an matrix.

  1. Check if the first row and first column already contain any zeros.
  2. Iterate through the rest of the matrix. If matrix[row][col] is 0, use the first cell of that row and column as flags (matrix[row][0] = 0 and matrix[0][col] = 0).
  3. Use those flags to zero out the inner cells of the grid.
  4. Finally, zero out the first row and column if your initial check (Step 1) was positive.
  5. Print the final matrix row-by-row, with elements separated by spaces.

01EXAMPLE 1

Input[[1,1,1],[1,0,1],[1,1,1]]
Output1 0 1 0 0 0 1 0 1

Explanation: Middle row and col zeroed.

Constraints

  • In-place (O(1) extra space excluding matrix storage).
MatrixLogic
JavaScript
Loading...
1 Hidden

Input Arguments

matrix[[1,1,1],[1,0,1],[1,1,1]]

Expected Output

1 0 1
0 0 0
1 0 1

Click RUN to test your solution