Skip to problem
←

Distance to the Nearest 1

Medium 0 attempts

Given a rectangular binary matrix grid containing at least one 1, return the distance from every cell to its nearest cell containing 1.

Distance is measured in horizontal or vertical steps: between (r, c) and (i, j), it is |r - i| + |c - j|. Diagonal steps are not allowed. A cell containing 1 has distance 0 from itself.

Function contract

grid is a nonempty rectangular matrix of 0s and 1s containing at least one 1.

Output: Return a matrix of the same dimensions; each entry is the minimum Manhattan distance to any cell containing 1.

Example 1

Input
grid = [[0,0,0],[0,1,0],[1,0,1]]
Output
[[2,1,2],[1,0,1],[0,1,0]]

Example 2

Input
grid = [[1,1]]
Output
[[0,0]]
Visual Aid
Nearest-source distances
Input000010101Distance212101010→

Shaded cells contain 1 in the input and have distance 0. Each horizontal or vertical step adds 1.

Constraints
  • 1 <= rows, cols <= 500
  • grid[i][j] is 0 or 1
  • At least one cell contains 1.

Multi-source BFS

Start BFS from all cells containing 1 simultaneously.

javascript
function nearestCell(grid) {
  const m = grid.length,
    n = grid[0].length;
  const dist = Array.from({ length: m }, () => Array(n).fill(Infinity));
  const q = [];
  for (let i = 0; i < m; i++)
    for (let j = 0; j < n; j++)
      if (grid[i][j] === 1) {
        dist[i][j] = 0;
        q.push([i, j]);
      }
  const dirs = [
    [0, 1],
    [0, -1],
    [1, 0],
    [-1, 0],
  ];
  let head = 0;
  while (head < q.length) {
    const [r, c] = q[head++];
    for (const [dr, dc] of dirs) {
      const nr = r + dr,
        nc = c + dc;
      if (nr >= 0 && nr < m && nc >= 0 && nc < n && dist[nr][nc] > dist[r][c] + 1) {
        dist[nr][nc] = dist[r][c] + 1;
        q.push([nr, nc]);
      }
    }
  }
  return dist;
}

Time: O(mn) | Space: O(mn)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript