Set Matrix Zeros

Try to solve the Set Matrix Zeros problem.

Statement#

Given a matrix, mat, if any element within the matrix is zero, set that row and column to zero.

Constraints:

  • 11 \le mat.row, mat.col 20\le 20
  • 231-2^{31} \le mat[i][j] 2311\le 2^{31} - 1

Examples#

Created with Fabric.js 3.6.6 Input Matrix Output Matrix Sample example 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 0 1 0 1 ------------------------------

1 of 3

Created with Fabric.js 3.6.6 Input Matrix Output Matrix Sample example 2 3 5 2 0 1 0 4 6 7 3 2 4 0 0 0 0 0 0 0 0 7 0 2 0 ------------------------------

2 of 3

Created with Fabric.js 3.6.6 Input Matrix Output Matrix Sample example 3 12 14 7 0 6 9 11 21 0 4 8 3 5 7 4 0 2 3 1 6 0 0 0 0 0 9 11 0 0 0 0 0 0 0 0 0 0 3 1 0 ------------------------------

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re are solving the correct problem:

Set Matrix Zeros

1

What is the correct output if the following matrix is given as input?

matrix=[123456709]matrix = \begin{bmatrix}1 & 2 & 3 \\4 & 5 & 6 \\ 7 & 0 & 9 \end{bmatrix}

A)

matrix=[020406000]matrix = \begin{bmatrix}0 & 2 & 0 \\4 & 0 & 6 \\ 0 & 0 & 0 \end{bmatrix}

B)

matrix=[103406000]matrix = \begin{bmatrix}1 & 0 & 3 \\4 & 0 & 6 \\ 0 & 0 & 0 \end{bmatrix}

C)

matrix=[103406709]matrix = \begin{bmatrix}1 & 0 & 3 \\4 & 0 & 6 \\ 7 & 0 & 9 \end{bmatrix}

D)

matrix=[123456000]matrix = \begin{bmatrix}1 & 2 & 3 \\4 & 5 & 6 \\ 0 & 0 & 0 \end{bmatrix}

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

If any element in first row and/or the first column is 0, set frow and fcol to TRUE.

Scan the complete matrix row-wise by ignoring the first row and, first column and set 0 in the first element of the particular row and column where 0 is found.

Check every row’s first element, starting from second row. If it is 0, then set all values in that row to 0.

Check every column’s first element starting from second column. If it is 0, then set all values in that column to 0.

If frow and/or fcol is TRUE, set first row or column to 0.


Try it yourself#

Implement your solution in the following coding playground.

Python
usercode > main.py
Input #1
Set Matrix Zeros

Matrices: Introduction

Solution: Set Matrix Zeros