Perfect Rank Private Jobs
Perfect RankPrivate Jobs
💼 Placement & IT Recruitment Prep
#4

Find a Safe Walk Through a Grid

Medium
Acceptance: 38.5%•ArrayBreadth-First SearchGraphHeap (Priority Queue)MatrixShortest Path•GoogleAmazonMicrosoftUberTCS DigitalInfosys DSE

Problem Statement

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 reach the lower-right corner (m - 1, n - 1).

You can move up, down, left, or right from any cell to its adjacent cells in 4 directions.

Each cell (r, c) has a value:

  • grid[r][c] == 1 is an unsafe cell, reducing your health by 1.
  • grid[r][c] == 0 is a safe cell, keeping your health unchanged.

You can walk through a cell only if your health remains strictly positive (health >= 1) after visiting that cell (including both the starting cell (0, 0) and the destination cell (m - 1, n - 1)).

Return true if you can reach (m - 1, n - 1) with health >= 1, or false otherwise.

Examples

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 path (0,0) → (1,0) → (2,0) → (2,1) → (2,2) → (1,2) → (0,2) → (0,3) → (0,4) → (1,4) → (2,4) contains only cells with value 0. Total health lost = 0. Final health = 1 - 0 = 1 >= 1. Hence, return true.

Example 2
Input: grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5
Output: true
Explanation:

The path (0,0) → (1,0) → (1,1) → (1,2) → (2,2) encounters 4 unsafe cells: grid[0][0]=1, grid[1][0]=1, grid[1][1]=0, grid[1][2]=1, grid[2][2]=1. Total health lost = 4. Final health = 5 - 4 = 1 >= 1. Hence, return true.

Example 3
Input: grid = [[1,1,1,1]], health = 4
Output: false
Explanation:

The only possible path visits all 4 cells, each with value 1. Total health lost = 4. Final health = 4 - 4 = 0. Since health must be >= 1, we cannot reach the destination safely. Hence, return false.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1
  • 1 <= health <= m + n

Hints

1
2
3
4
5
6
7
8
9
10
Input (grid, health):
Student & User Feedback

How was your experience on this page?

Your review & improvement suggestions help us refine tools, mock tests, and explanations — it takes only 10 seconds!

Feedback goes directly to our team at perfectrankofficial@gmail.com
Outstanding / Excellent! 🌟
Back to Top of Private Jobs Portal