Grid Distance to the Closest Marked Cell
Trees & GraphsAuto-graded · 19 test casesLast updated
Compute, for every cell of a grid, the fewest orthogonal steps to the closest marked cell, using a single multi-source breadth-first search; -1 everywhere when no cell is marked.
You are given a rectangular grid of integers with m rows and n columns. A cell holding 1 is a marked cell, and a cell holding 0 is an ordinary cell.
From any cell you may step to one of its four orthogonal neighbours (up, down, left, right), and each step costs exactly 1. Steps may not leave the grid, and every cell can be entered regardless of its value.
Build and return a matrix of the same shape in which each entry is the minimum number of steps needed to get from that cell to the closest marked cell.
Rules for the output:
- A marked cell has distance
0. - If the grid contains no marked cell at all, every entry of the result is
-1. - If the input grid is empty (
[]), return[]. - The input grid must not be relied upon to be modified; return a new matrix.
Constraints
0 <= m, n- Every cell is either
0or1. - All rows have the same length.
- Distances are measured only with 4-directional moves (no diagonals).
- The result has the same dimensions as the input.
Examples
Example 1
Input: closest_marked_distance([[0, 0, 0], [0, 1, 0], [0, 0, 0]])
Output: [[2, 1, 2], [1, 0, 1], [2, 1, 2]]
Example 2
Input: closest_marked_distance([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]])
Output: [[0, 1, 2, 2], [1, 2, 2, 1], [2, 2, 1, 0]]
Example 3
Input: closest_marked_distance([[0, 0], [0, 0]])
Output: [[-1, -1], [-1, -1]]
Hints
Hint 1
Computing a separate search from every cell, or from every marked cell, repeats a lot of work. Think about how to start one search that covers all marked cells together.
Hint 2
Put every marked cell into the queue at distance 0 before the search begins, then expand level by level. The first time a cell is reached, that distance is already the smallest possible.
Hint 3
Use a result matrix filled with -1 that also serves as the visited marker. Assign a value only to cells still holding -1. Handle the empty grid up front, and note that with no marked cells the queue starts empty, leaving all -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a shortest-path problem on an unweighted graph where each cell is a node and edges join orthogonal neighbours. We want the distance to the nearest of many targets.
Two simple ideas are too slow. Searching from every cell until a marked cell is found can cost O((mn)^2) overall. Searching from each marked cell and keeping the minimum costs O(k * mn) for k marked cells.
Instead, run one multi-source breadth-first search:
- Create a result matrix filled with
-1. A value of-1means "not reached yet". - Scan the grid. For every marked cell, set its result to
0and push it onto the queue. - Repeatedly pop a cell, look at its four neighbours, and for each in-bounds neighbour still holding
-1, set it to the current distance plus one and push it. - When the queue is empty, return the result matrix.
An empty grid returns [] immediately. If there are no marked cells, the queue starts empty, so nothing changes and every entry stays -1, which matches the required output.
Why it is correct
BFS processes cells in non-decreasing order of distance. The queue initially contains all distance-0 cells, and from then on it holds cells of some distance d followed by cells of distance d + 1. Suppose a cell is first reached from a neighbour at distance d and gets d + 1. If a shorter path to a marked cell existed, the cell's neighbour on that path would have a distance smaller than d and would have been processed earlier, reaching the cell first. That contradicts the assumption, so the first assignment is the minimum. Because we only write to cells still equal to -1, values are never overwritten.
Complexity
- Time: O(m * n), since each cell is enqueued and dequeued at most once and checks four neighbours.
- Space: O(m * n) for the result matrix and the queue.
Reference solution
from collections import deque
from typing import List
def closest_marked_distance(grid: List[List[int]]) -> List[List[int]]:
if not grid:
return []
m, n = len(grid), len(grid[0])
dist = [[-1] * n for _ in range(m)]
queue = deque()
for r in range(m):
for c in range(n):
if grid[r][c] == 1:
dist[r][c] = 0
queue.append((r, c))
while queue:
r, c = queue.popleft()
nxt = dist[r][c] + 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and dist[nr][nc] == -1:
dist[nr][nc] = nxt
queue.append((nr, nc))
return dist