FastPrepShortest Grid Path With One Wall Break

Shortest Grid Path With One Wall Break

Amazon logoAmazonâ—Ź MediumINTERNPHONE SCREEN

Problem statement

Given a rectangular binary matrix grid, a cell containing 1 is open and a cell containing 0 is a wall.

Start at the top-left cell and move to the bottom-right cell. Each move goes one cell up, down, left, or right. During the route, you may break and enter at most one wall.

Return the minimum number of moves needed to reach the destination, or -1 when no valid route exists.

Function

minimumMovesWithOneWallBreak(grid: int[][]) → int

Examples

Example 1

grid = [[1,0,1],[0,0,1],[1,1,1]]return = 4

Break the wall at (0,1), then move through (0,2) and (1,2) to reach (2,2) in four moves.

Example 2

grid = [[1,0,1],[0,0,0],[1,0,1]]return = -1

Every route from the start to the destination would enter at least two wall cells, so one wall break is insufficient.

Example 3

grid = [[1]]return = 0

The start is already the destination, so no move is needed.

Constraints

  • 1 <= grid.length <= 200
  • 1 <= grid[i].length <= 200
  • Every row has the same length.
  • grid[i][j] is either 0 or 1.
  • The top-left and bottom-right cells contain 1.

More Amazon problems

See Amazon hiring insights
Saved
public int minimumMovesWithOneWallBreak(int[][] grid) {
  // write your code here
}
Checking account…