KatInterview

Grid Distance to the Closest Marked Cell

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsmulti-source-bfsgrid

Last 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 0 or 1.
  • 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.