You are given an m x n binary matrix grid and an integer health.
You start on the upper-left corner (0, 0) and would like to get to the lower-right corner (m - 1, n - 1).
You can move up, down, left, or right from one cell to another adjacent cell as long as your health remainspositive.
Cells (i, j) with grid[i][j] = 1 are considered unsafe and reduce your health by 1.
Return true if you can reach the final cell with a health value of 1 or more, and false otherwise.
Example 1:
Input:grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1
Output:true
Explanation:
The final cell can be reached safely by walking along the gray cells below.
Example 2:
Input:grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3
Output:false
Explanation:
A minimum of 4 health points is needed to reach the final cell safely.
Example 3:
Input:grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5
Output:true
Explanation:
The final cell can be reached safely by walking along the gray cells below.
Any path that does not go through the cell (1, 1) is unsafe since your health will drop to 0 when reaching the final cell.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
2 <= m * n
1 <= health <= m + n
grid[i][j] is either 0 or 1.
Solutions
Solution 1: BFS
Thinking
A \(1\)-cell costs one health; we must reach the end with health left. \(m,n\le 50\). A visited-only BFS is not enough, because a cheaper path may arrive later.
\(dist[i][j]\) is the least cost to that cell; a successful relaxation enqueues. Weights are \(0/1\), so the queue BFS is valid. The end is safe iff that cost is strictly below \(\textit{health}\).
We define a 2D array \(\textit{dist}\), where \(\textit{dist}[i][j]\) represents the minimum health value required to reach position \((i, j)\) from the top-left corner. Initially, we set \(\textit{dist}[0][0]\) to \(\textit{grid}[0][0]\) and add \((0, 0)\) to the queue \(\textit{q}\).
Then, we continuously take elements \((x, y)\) from the queue and try to move in four directions. If we move to a valid position \((nx, ny)\) and the health value required to move from \((x, y)\) to \((nx, ny)\) is smaller, we update \(\textit{dist}[nx][ny] = \textit{dist}[x][y] + \textit{grid}[nx][ny]\) and add \((nx, ny)\) to the queue \(\textit{q}\).
Finally, when the queue is empty, we obtain \(\textit{dist}[m-1][n-1]\), which is the minimum health value required to reach the bottom-right corner from the top-left corner. If this value is less than \(\textit{health}\), then we can reach the bottom-right corner; otherwise, we cannot.
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Here, \(m\) and \(n\) are the number of rows and columns of the grid, respectively.