Distance of Nearest Cell Having 1

medium

Given an R × C grid of 0s and 1s, for every cell compute the distance (number of 4-directional steps) to the nearest cell containing a 1. A cell that already holds a 1 has distance 0. Return the grid of distances. (If the grid has no 1 at all, every distance is -1.)

Hints

Don't BFS from every cell — seed one BFS from all the 1s at once.
Every 1-cell starts at distance 0.
The first time BFS reaches a cell, that's its distance to the nearest 1.

Common doubts

BFS settles cells in nondecreasing distance order, so a cell is first reached by the wave from its closest source.
All 1-cells share the initial queue at distance 0, so every cell measures to whichever source is nearest.
No sources means no distances — every cell stays -1.

Interview follow-ups

Seed from all 0-cells instead — it's the same algorithm (LeetCode 542).
Yes — two sweeps (top-left then bottom-right) propagate the nearest distance in O(R·C) without a queue.

Fun facts

  • This is the mirror of LeetCode 542 (0-1 matrix): sources are the 1s instead of the 0s.
  • Multi-source BFS is the grid version of adding a virtual super-source connected to all sources.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[2,1,2],[1,0,1],[2,1,2]]
Distances radiate outward from the single 1.
Example 2
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: [[0,1,0],[1,2,1],[0,1,0]]
Each cell takes the closest of the four corner 1s.
Constraints

- 1 <= R, C <= 500 - grid[i][j] is 0 or 1

Solve this problem →