oneby7

Graphs Fewest steps with BFS

443. 01 Matrix

Medium 147 DSA Sheet

You are given a grid mat in which every cell holds 0 or 1. For every cell, find the distance to the nearest cell that holds 0. Return these distances as a grid of the same size.

The distance between two cells is the number of steps it takes to walk from one to the other. A step moves to the cell directly above, below, left or right. Diagonal steps are not allowed. A cell that holds 0 has distance 0.

Example 1

011111101111
mat
012112102321
output

Input: mat = [[0, 1, 1, 1], [1, 1, 1, 0], [1, 1, 1, 1]]

Output: [[0,1,2,1],[1,2,1,0],[2,3,2,1]]

Explanation: The cell at row 2, column 1 is three steps from either 0, the most of any cell. The cell at row 0, column 2 is two steps from both 0s.

Example 2

110111
mat
210123
output

Input: mat = [[1, 1, 0, 1, 1, 1]]

Output: [[2,1,0,1,2,3]]

Explanation: The only 0 is in column 2. Each cell's distance is how far its column is from column 2.

Example 3

111101111
mat
212101212
output

Input: mat = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]

Output: [[2,1,2],[1,0,1],[2,1,2]]

Explanation: The corners touch the 0 only at a corner, so each one needs two steps, such as one right and one down.

Check your understanding

Work out the answer for this input before you write any code.

mat = [[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 0]]

Constraints

  • m == mat.length, n == mat[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • mat[i][j] is 0 or 1.
  • mat holds at least one 0.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.