LeetCode 3286: Find a Safe Walk Through a Grid
Problem Description
Explanation:
To solve this problem, we can use Depth-First Search (DFS) to explore all possible paths from the start cell to the end cell while keeping track of the health remaining at each step. If we reach the destination cell with positive health, we return true; otherwise, we return false. We need to mark the cells already visited to avoid revisiting them in the path.
- Create a helper function
dfs
that takes the current position(x, y)
, current health remaining, and the grid as parameters. - Check if the current position is out of bounds or if the health is not enough to continue. If so, return false.
- Check if the current position is the destination cell. If so, return true.
- Mark the current position as visited by setting it to -1 in the grid.
- Recursively explore all valid neighboring cells (up, down, left, right) with updated health.
- If any of the recursive calls return true, propagate true up the call stack.
- If no valid path is found, backtrack by marking the current cell as unvisited and return false.
Time Complexity: O(m * n) where m and n are the dimensions of the grid. Space Complexity: O(m * n) for the recursive call stack.
Solutions
class Solution {
public boolean findSafeWalk(int[][] grid, int health) {
return dfs(0, 0, health, grid);
}
private boolean dfs(int x, int y, int health, int[][] grid) {
if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || health <= 0 || grid[x][y] == -1) {
return false;
}
if (x == grid.length - 1 && y == grid[0].length - 1) {
return true;
}
grid[x][y] = -1;
boolean result = dfs(x + 1, y, grid);
result |= dfs(x - 1, y, grid);
result |= dfs(x, y + 1, grid);
result |= dfs(x, y - 1, grid);
grid[x][y] = 0;
return result;
}
}
Loading editor...