Find a Safe Walk Through a Grid Problem
Description
LeetCode Problem 3286.
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 remains positive.
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.lengthn == grid[i].length1 <= m, n <= 502 <= m * n1 <= health <= m + ngrid[i][j]is either 0 or 1.
Solution
Approach: Shortest Path (BFS with Relaxation)
Stepping onto a cell costs its value (1 for an unsafe cell, 0 otherwise), and the start cell costs grid[0][0] too. We want the cheapest path to the bottom-right cell, and the walk is possible when that cost is less than health (we need at least 1 health left).
Keep dist[x][y], the lowest cost found so far to reach each cell. Push (0, 0) into a queue and, for every cell taken from it, try its four neighbours: whenever going through the current cell gives a smaller cost, update the neighbour and queue it. When the queue is empty, return whether dist[m - 1][n - 1] < health.
Complexity:
- Time complexity:
O(m * n * (m + n))in the worst case, since costs are at mostm + n - Space complexity:
O(m * n)
from collections import deque
from math import inf
class Solution:
def findSafeWalk(self, grid: List[List[int]], health: int) -> bool:
m, n = len(grid), len(grid[0])
dist = [[inf] * n for _ in range(m)]
dist[0][0] = grid[0][0]
q = deque([(0, 0)])
dirs = (-1, 0, 1, 0, -1)
while q:
x, y = q.popleft()
for a, b in zip(dirs, dirs[1:]):
nx, ny = x + a, y + b
if (
0 <= nx < m
and 0 <= ny < n
and dist[nx][ny] > dist[x][y] + grid[nx][ny]
):
dist[nx][ny] = dist[x][y] + grid[nx][ny]
q.append((nx, ny))
return dist[-1][-1] < health