Grokking 75: Top Coding Interview Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Shortest Path in a Grid with Obstacles Elimination (hard)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

You are given an m x n binary matrix grid where each cell is either empty (0) or has an obstacle (1). You can move up, down, left, or right, but only through empty cells. You can remove up to k obstacles along the way.

Return the shortest path from the top-left corner (0, 0) to the bottom-right corner (m - 1, n - 1). If it's not possible to reach the end, return -1.

Examples

Example 1

  • Input: k = 1, grid =
[[0, 1, 0, 0],
 [1, 1, 0, 1],
 [0, 0, 0, 0],
 [0, 1, 1, 0]]

  • Expected Output: 6

  • Justification: You can remove one obstacle to create a path from (0, 0) to (3, 3). The path can be (0,0) → (0,1) → (0,2) → (1,2) → (2,2) → (2,3) → (3,3). Here, we have removed the obstacle from (0, 1) position.

Example 2

  • Input: k = 2, grid =
  [[0, 0, 0],
   [1, 1, 0],
   [1, 1, 0],
   [0, 0, 0]]
  • Expected Output: 5
  • Justification: You can remove two obstacles to create a path from (0, 0) to (3, 2). The path can be (0,0) → (0,1) → (0,2) → (1,2) → (2,2) -> (3, 2). Here, we don't need to remove any obstacles.

Example 3

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

  • Justification: You can remove three obstacles to create a path from (0, 0) to (3, 2). The path can be (0,0) → (0,1) → (0,2) → (1,2) → (2,2) → (3,2). Here, we have removed the obstacle from (0, 2) position.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 40
  • 1 <= k <= m * n
  • grid[i][j] is either 0 or 1.
  • grid[0][0] == grid[m - 1][n - 1] == 0

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible