Understanding the Problem
You are given a binary grid (a 2D matrix of 0s and 1s). For each cell, you must find the distance to the nearest cell that has the value 1
. The distance is calculated in terms of steps to adjacent (top, bottom, left, or right) cells — diagonals are not allowed.
Case 1: All Cells are 1
If all the cells in the grid contain 1, then the distance for every cell is 0 — it is already a 1, so the nearest 1 is itself.
Case 2: No Cell Contains 1
If there are no 1s in the grid, it's impossible to find a distance to a 1. In practice, such a case might be handled by returning -1 or leaving the distance matrix filled with a sentinel value (like Infinity).
Case 3: Mixed 0s and 1s
This is the most typical scenario. To find the minimum distance efficiently for each cell, we perform a multi-source BFS starting from all the cells that already contain a 1. Initially, all 1s are added to a queue with a distance of 0. As BFS proceeds, we update the distance of each 0-cell as it is reached for the first time by expanding from neighboring 1s.
Why Breadth-First Search?
BFS ensures that we reach each cell using the shortest path from the nearest 1. By exploring all directions level by level, the first time we visit a cell will be through the shortest possible path.
Result
The final result is a grid of the same size, where each cell contains the shortest number of steps to reach the nearest cell with a 1.