Navigate Through a Dangerous Grid

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
Find a Safe Walk Through a Grid INPUT 3x5 Grid (0=safe, 1=trap) 0 1 0 0 0 0 1 0 1 0 0 0 0 1 0 START END Safe (0) Trap (1) Input Values grid = [[0,1,0,0,0], [0,1,0,1,0], [0,0,0,1,0]] health = 1 ALGORITHM STEPS 1 Use BFS/0-1 BFS Track max health at each cell 2 Start at (0,0) Initial health = 1 3 Explore Neighbors Subtract 1 if trap cell 4 Check Destination Return true if health >= 1 Optimal Path Found: END All cells on path are safe (0) Health remains 1 throughout FINAL RESULT Safe path Avoided traps Output: true Safe path exists! Path length: 11 steps Traps avoided: 4 Final health: 1 (OK) Key Insight: Use 0-1 BFS (deque) for optimal pathfinding. Safe cells have edge weight 0, trap cells have weight 1. Track maximum remaining health at each cell. The path exists if we can reach destination with health >= 1. TutorialsPoint - Find a Safe Walk Through a Grid | Optimal Solution (0-1 BFS)
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15 Apple 12
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen