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,1,0],[0,0,0]]
›
Output:
2
💡 Note:
With one thief at the center (1,1), the optimal path (0,0) → (0,1) → (0,2) → (1,2) → (2,2) maintains minimum distance 2 from the thief.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code