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
Find the Safest Path in a Grid INPUT 1 0 0 0 0 0 0 0 1 T T Thief (1) Empty (0) Start (0,0) End (2,2) grid = [[1,0,0],[0,0,0],[0,0,1]] ALGORITHM (BFS) 1 Multi-source BFS Compute distance to nearest thief for all cells 2 Build Distance Grid Manhattan distance from each cell to closest thief 0 1 2 1 1 1 2 1 0 3 Binary Search + BFS Find max safeness where path exists from start to end 4 Check Start/End Start cell has thief: dist=0 So safeness = 0 FINAL RESULT S E Path shown: one possible route (0,0) is adjacent to thief Min distance on path = 0 OUTPUT 0 Safeness Factor = 0 (Start cell touches thief) Key Insight: Use Multi-source BFS from all thieves to compute Manhattan distance for every cell. Then use Binary Search on safeness value + BFS to check if a valid path exists. Since start (0,0) has a thief, the safeness is 0 regardless of the path taken. Time: O(n^2 log n), Space: O(n^2) TutorialsPoint - Find the Safest Path in a Grid | BFS Approach
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28 Apple 22
52.4K Views
Medium Frequency
~25 min Avg. Time
1.8K 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