Find a Safe Walk Through a Grid - Problem
Navigate Through a Dangerous Grid
You are an adventurer exploring a treacherous
Grid Rules:
• Move only to adjacent cells (up, down, left, right)
• Safe cells
• Unsafe cells
• You must maintain positive health throughout your journey
Return
Think of it as finding the safest path through a minefield while managing your limited health points!
You are an adventurer exploring a treacherous
m × n grid where some cells are unsafe traps. Starting at the top-left corner (0, 0) with a given health value, your goal is to reach the bottom-right corner (m-1, n-1) while staying alive.Grid Rules:
• Move only to adjacent cells (up, down, left, right)
• Safe cells
(grid[i][j] = 0) don't affect your health• Unsafe cells
(grid[i][j] = 1) reduce your health by 1• You must maintain positive health throughout your journey
Return
true if you can reach the destination with health ≥ 1, false otherwise.Think of it as finding the safest path through a minefield while managing your limited health points!
Input & Output
basic_path.py — Basic Safe Path
$
Input:
grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1
›
Output:
true
💡 Note:
Starting with health=1, we can take path (0,0)→(1,0)→(2,0)→(2,1)→(2,2)→(2,3)→(2,4). We encounter 0 unsafe cells initially, so we never lose health below 1.
insufficient_health.py — Insufficient Health
$
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
💡 Note:
With health=3, every possible path to reach (3,5) requires going through more than 3 unsafe cells, which would reduce health to 0 or below.
minimal_health.py — Edge Case
$
Input:
grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5
›
Output:
true
💡 Note:
Starting with health=5, optimal path is (0,0)→(0,1)→(0,2)→(1,2)→(2,2). We lose 4 health total (1+1+1+1), ending with health=1 at destination.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 50
- 1 ≤ health ≤ m + n + 1
- grid[i][j] is either 0 or 1
- You must maintain positive health throughout the journey
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code