Loading content...
You are navigating a terrain represented as a 0-indexed two-dimensional grid of dimensions m × n. Each cell in this grid contains one of two possible values:
From any passable cell, you may move in four cardinal directions: up, down, left, or right, as long as the destination cell is within the grid boundaries.
Your objective is to find a path from the top-left corner at position (0, 0) to the bottom-right corner at position (m - 1, n - 1). To accomplish this, you may need to clear some barriers along the way to create a viable path.
Return the minimum number of barriers that must be cleared to establish a traversable route from the starting position to the destination. The starting and ending cells are always guaranteed to be passable (value 0).
This is a classic example of weighted shortest path problems on a grid. Understanding how to adapt BFS for weighted graphs (particularly with constrained weights like 0 and 1) is crucial for:
grid = [[0,1,1],[1,1,0],[1,1,0]]2The grid is a 3×3 terrain where most cells are barriers (1s). Starting from (0,0), we need to find a path to (2,2). One optimal strategy is to clear the barriers at positions (0,1) and (0,2), allowing us to traverse the path: (0,0) → (0,1) → (0,2) → (1,2) → (2,2). This requires clearing exactly 2 barriers. It can be proven that no path exists with fewer barrier removals.
grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]0In this 3×5 grid, there exists a clear path from (0,0) to (2,4) that doesn't require removing any barriers. One such path is: (0,0) → (1,0) → (2,0) → (2,1) → (2,2) → (1,2) → (0,2) → (0,3) → (0,4) → (1,4) → (2,4). Since all cells along this path are passable (value 0), no barriers need to be cleared.
grid = [[0,0,1],[1,0,1],[1,0,0]]0The grid has a clear corridor of passable cells running vertically through column 1, then horizontally along row 2. The path (0,0) → (0,1) → (1,1) → (2,1) → (2,2) reaches the destination without encountering any barriers, so the answer is 0.
Constraints