Skip to main content
Back to problems
Leetcode
Medium
Matrices
Graphs
Heaps
Google
Meta
Find The Safest Path In A Grid

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.

Acceptance 0%
Problem Statement

Problem

You are given an n×nn \times n 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 (0,0)(0,0) to (n−1,n−1)(n-1,n-1).

Notes

  • Dangerous cells are typically marked with 1, and safe cells with 0.
  • The Manhattan distance between two cells (r1,c1)(r_1,c_1) and (r2,c2)(r_2,c_2) is ∣r1−r2∣+∣c1−c2∣|r_1-r_2| + |c_1-c_2|.
  • 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 n binary grid, where 1 denotes a dangerous cell and 0 denotes 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

  • 1≤n≤4001 \le n \le 400
  • The grid is square.
  • Each cell is either 0 or 1.
  • There is at least one valid path from start to finish under four-directional movement.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.