← DiffPush

01 Matrix — Distance to Nearest Zero

Standard Bar Graphs · Traversal Problems O(m * n) · O(m * n)

Nearest Extinguisher Mapping

A data-hall floor plan marks equipment racks (1) and extinguisher stations (0). For every rack cell, the safety map must state the walking distance — steps across edge-adjacent floor cells — to the closest extinguisher. Stations themselves report 0.

Input: An m x n binary matrix mat containing at least one 0.

Output: Return an m x n matrix where each cell holds the distance to its nearest 0.

Constraints

Examples

Example 1

Input: {"mat":[[0,0,0],[0,1,0],[0,0,0]]}
Output: [[0,0,0],[0,1,0],[0,0,0]]
The lone rack sits one step from extinguishers on every side.

Example 2

Input: {"mat":[[0,0,0],[0,1,0],[1,1,1]]}
Output: [[0,0,0],[0,1,0],[1,2,1]]
Distances ripple outward from the zero row; the far corner needs two steps.

Solve this in your browser →

Also on LeetCode ↗