Find the Safest Path in a Grid - Problem
You're trapped in a dangerous n ร n grid filled with thieves, and you need to find the safest possible path from the top-left corner (0, 0) to the bottom-right corner (n-1, n-1)!
The grid contains:
- Thieves at positions where
grid[r][c] = 1 - Empty cells where
grid[r][c] = 0
You can move to any adjacent cell (up, down, left, right) in each step. The safeness factor of any path is defined as the minimum Manhattan distance from any cell in your path to the nearest thief.
Goal: Find the path that maximizes this safeness factor - stay as far away from thieves as possible!
Manhattan distance between cells (a,b) and (x,y) = |a-x| + |b-y|
Input & Output
example_1.py โ Basic Grid
$
Input:
grid = [[1,0,0],[0,0,0],[0,0,1]]
โบ
Output:
0
๐ก Note:
All paths from (0,0) to (2,2) must pass through cells adjacent to thieves. The maximum safeness factor is 0 since we can't avoid being adjacent to thieves.
example_2.py โ Safe Path Exists
$
Input:
grid = [[0,0,1],[1,0,0],[0,0,0]]
โบ
Output:
1
๐ก Note:
The safest path is (0,0) โ (0,1) โ (1,1) โ (2,1) โ (2,2). The minimum distance to any thief along this path is 1.
example_3.py โ No Thieves
$
Input:
grid = [[0,0,0],[0,0,0],[0,0,0]]
โบ
Output:
4
๐ก Note:
With no thieves in the grid, we can define the safeness as the maximum possible distance, which would be 4 for a 3x3 grid (from corner to opposite corner).
Constraints
- 1 โค n โค 400
- grid[i][j] is either 0 or 1
- There is at least one thief in the grid
- Manhattan distance = |xโ - xโ| + |yโ - yโ|
- Time limit: 3 seconds
Visualization
Tap to expand
Understanding the Visualization
1
Map Danger Zones
Calculate how far each room is from the nearest intruder using flood-fill
2
Define Safety Threshold
Use binary search to find the maximum safe distance we can maintain
3
Find Safe Route
For each threshold, check if a valid path exists using only sufficiently safe rooms
4
Optimize Path
The answer is the highest safety threshold for which a path exists
Key Takeaway
๐ฏ Key Insight: By precomputing distances to all thieves and using binary search, we can efficiently find the maximum safeness factor without exploring every possible path.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code