All problems
0278MediumArrayDynamic ProgrammingBreadth-First SearchMatrix

Steps to the Nearest Air Shaft

Tracked in this browser only
Write code

Trains the technique from

LeetCode 54201 Matrix

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A mine level is surveyed as a rectangular grid of cells. grid[r][c] is 0 when the cell holds a ventilation shaft and 1 when it is plain rock. At least one cell holds a shaft.

A surveyor moves between cells that share an edge, one step per move, and every cell of the level can be walked through whatever its marking. Diagonal moves are not possible.

For every cell report the fewest steps from that cell to a cell holding a shaft; a cell that holds a shaft reports 0. Return these counts in a grid of the same shape as grid.

Examples

Example 1

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

The one shaft sits at row 0, column 0. The cell at row 1, column 1 reaches it with one step up and one step left, so it reports 2, and the opposite corner reports 4.

Example 2

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

The shaft sits at row 0, column 2. The cell at row 1, column 0 walks right, right and up, so it reports 3.

Example 3

Input
grid = [[0]]
Output
[[0]]

The single cell holds a shaft, so no steps are needed.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10^4
  • 1 <= m * n <= 10^4
  • grid[i][j] is either 0 or 1.
  • There is at least one 0 in grid.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def steps_to_nearest_shaft(grid: list[list[int]]) -> list[list[int]]:
Java
public int[][] stepsToNearestShaft(int[][] grid)
September 7
Apply