Find the Safest Path in a Grid

You are given an n x n grid where grid[r][c] = 1 marks a thief and 0 an empty cell. You start at (0, 0) and must reach (n - 1, n - 1), moving up, down, left or right (you may step on any cell, thieves included). The safeness factor of a path is the smallest Manhattan distance from any cell on the path to any thief. Return the maximum safeness factor over all paths.

30:00

Find the Safest Path in a Grid
medium
Free written solution
Topics
Companies

You are given an n x n grid where grid[r][c] = 1 marks a thief and 0 an empty cell. You start at (0, 0) and must reach (n - 1, n - 1), moving up, down, left or right (you may step on any cell, thieves included). The safeness factor of a path is the smallest Manhattan distance from any cell on the path to any thief. Return the maximum safeness factor over all paths.

Example 1:
Input: {"grid":[[1,0,0],[0,0,0],[0,0,1]]}
Output: 0
Constraints:
  • 1≤n==grid.length==grid[i].length≤4001 \leq n == \text{grid.length} == \text{grid}[i].\text{length} \leq 400

  • grid[i][j]\text{grid}[i][j] is 0 or 1

  • There is at least one thief in the grid.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[1,0,0],[0,0,0],[0,0,1]]}

A 3 x 3 grid. First measure every cell's distance to its nearest thief, then find the route whose closest call is as far as possible.

T

T

thief (T)

waiting in a bucket

route / current

Variables
No variables to display
DepthFunction Call
Stack empty
0/10