All problems
0354HardArrayBreadth-First SearchMatrix

Debris Field Crossing

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1293Shortest Path in a Grid with Obstacles Elimination

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 survey drone has to cross a debris field mapped as grid. It starts on the cell in the top-left corner and has to reach the cell in the bottom-right corner. A cell holding 1 is blocked by debris and a cell holding 0 is clear; both corner cells are clear.

One move carries the drone to a cell that shares an edge with the cell it is on. The drone carries k clearance charges: entering a blocked cell spends one charge and turns nothing else, and with no charges left the drone cannot enter a blocked cell at all. Charges are never recovered.

Return the fewest moves the drone needs to reach the far corner, or -1 when the trip is impossible within the charges it carries.

Examples

Example 1

Input
grid = [[0,0,1,0],[0,0,1,1],[1,0,1,0]], k = 1
Output
5

The drone moves right, then down twice to the cell in row 2 column 1, spends its charge entering the blocked cell in row 2 column 2, and steps right into the corner. That is five moves.

Example 2

Input
grid = [[0,1,0],[1,0,0],[1,1,1],[1,0,0]], k = 3
Output
5

One route of five moves spends a charge entering row 1 column 0, steps right, spends a second charge entering row 2 column 1, then goes down and right to the corner. It uses two of the three charges.

Example 3

Input
grid = [[0,1,1],[1,1,1],[1,1,0]], k = 1
Output
-1

Every route from one corner to the other passes through three blocked cells, and the drone carries a single charge, so it can never arrive.

Constraints

  • m == grid.length
  • n == grid[r].length
  • 1 <= m, n <= 40
  • 1 <= k <= m * n
  • grid[r][c] is 0 or 1.
  • grid[0][0] == 0 and grid[m - 1][n - 1] == 0

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 shortest_path(grid: list[list[int]], k: int) -> int:
Java
public int shortestPath(int[][] grid, int k)
September 7
Apply