26 · Graphs: BFS & DFS

#542 01 Matrix

Mediumsolve on LeetCode ↗

frequently reported atFlipkartAmazonGoogleMicrosoftMeta

the problem

In plain words

A matrix holds 0s and 1s, with at least one 0. For every cell, find how many steps (up, down, left, right) it takes to reach the nearest 0. Return those distances as a matrix of the same size.

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

out [[0,0,0],[0,1,0],[0,0,0]]

The middle 1 has a 0 right next to it.

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

out [[0,0,0],[0,1,0],[1,2,1]]

The bottom-middle 1 is 2 steps from the nearest 0 — for example up, then up again.

  • 1 ≤ m, n ≤ 10⁴
  • 1 ≤ m · n ≤ 10⁴
  • mat[i][j] is 0 or 1
  • At least one 0

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #286
      Walls and Gates
      Mediumin GraphsLeetCode Premium
    2. #994
      Rotting Oranges
      Mediumin Graphs
    3. #1091