Find a path from the top-left to the bottom-right of a grid that maximizes the minimum distance to any dangerous cell along the route.
Problem
You are given an grid where some cells are dangerous and the rest are safe. A path starts at the top-left cell and ends at the bottom-right cell, moving only in the four cardinal directions and never leaving the grid.
For any cell on a path, define its safeness as the Manhattan distance to the nearest dangerous cell. The safeness factor of a path is the minimum safeness among all cells on that path.
Return the largest possible safeness factor among all valid paths from to .
Notes
- Dangerous cells are typically marked with
1, and safe cells with0. - The Manhattan distance between two cells and is .
- If a path can avoid dangerous cells entirely, its safeness factor may be greater than 0.
Input Format
Input Format
- An integer
n, the size of the square grid. - An
n x nbinary grid, where1denotes a dangerous cell and0denotes a safe cell.
Output Format
Output Format
- Return one integer: the maximum safeness factor achievable for a path from the top-left to the bottom-right cell.
Constraints
Constraints
- The grid is square.
- Each cell is either
0or1. - There is at least one valid path from start to finish under four-directional movement.
Example 1
Input
grid = [[1,0,0],[0,0,0],[0,0,1]]
Output
0
Explanation
The start cell and the end cell are dangerous, so any valid path must include a cell with safeness 0. Therefore the best achievable safeness factor is 0.
Example 2
Input
grid = [[0,0,1],[0,0,0],[1,0,0]]
Output
1
Explanation
Every path from the top-left to the bottom-right can stay at least distance 1 away from the nearest dangerous cell, and no path can guarantee distance 2 throughout.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.