MediumArrayBinary SearchBreadth-First SearchUnion FindHeapMatrixUpdated Sep 2026

2812. Find the Safest Path in a Grid

Asked at Uber

Difficulty

Medium

Time

O(n^2 log n)

Space

O(n^2)

Pattern

Array

Companies

1

Problem

You are given an n x n grid. A cell with value 1 holds a thief, and a cell with value 0 is empty. You start at the top-left cell (0, 0) and want to reach the bottom-right cell (n - 1, n - 1). In one move you may step to a cell that shares an edge with your current cell (up, down, left, right). You are allowed to walk on thief cells.

The safeness factor of a path is the smallest Manhattan distance between any cell on that path and any thief in the whole grid. In other words, look at every cell you visit, measure its distance to the closest thief, and take the minimum of those numbers.

Return the largest safeness factor you can get over all paths from the start to the goal.

What the safeness factor measures

grid012012001000000One thief sits at (0,2), marked reddist to nearest thief012012210211222The start (0,0) is 2 away, so any path through itscores at most 2
Each cell's number is its distance to the nearest thief; a path's safeness is the smallest number along it.

Constraints

  • ●1 <= grid.length == n <= 400
  • ●grid[i].length == n
  • ●grid[i][j] is either 0 or 1
  • ●There is at least one thief in the grid

Examples

Example 1
Inputgrid = [[1,0,0],[0,0,0],[0,0,1]]
Output0
WhyBoth the start cell (0,0) and the goal cell (2,2) contain thieves, so every path includes a cell whose distance to a thief is 0. The minimum can never be above 0.
Example 2
Inputgrid = [[0,0,1],[0,0,0],[0,0,0]]
Output2
WhyThe only thief is at (0,2). The path that goes down the left side and then right stays far from it: the closest cell on that path to the thief is (0,0), at distance |0-0| + |0-2| = 2. No path can do better, so the answer is 2.
Example 3
Inputgrid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
Output2
WhyThe thieves are at (0,3) and (3,0). A path through the middle keeps distance 2 from both: cell (1,2) is 2 away from (0,3), and cell (3,2) is 2 away from (3,0). Getting closer to either thief would push the minimum below 2, so 2 is the best possible.

Asked At

1 companies
CompanyDifficulty
UberMediumView all Uber questions →

How to Think About It

1

Brute force: enumerate all paths (exponential) and compute safety for each — infeasible.

2

Compute Manhattan distance from every cell to nearest thief using multi-source BFS.

3

Binary search on the safety threshold: for a given value mid, check if a valid path exists using only cells with distance >= mid.

4

Alternatively use a max-heap (priority queue) starting from (0,0), always expanding the cell with highest safety.

5

Both approaches are O(n^2 log n) — binary search uses BFS/DFS per check, heap approach is single-pass with heap ops.

Optimal Approach

First, run a multi-source BFS from all thief cells to compute the minimum Manhattan distance from every cell to the nearest thief. Then binary search on the safety value: for each candidate mid, check if a path exists from (0,0) to (n-1,n-1) using only cells whose distance is at least mid. The check is a simple BFS/DFS. Return the largest mid that yields a valid path. Time complexity is O(n^2 log n).

Distance map, then binary search

dist012012210211222Step 1 — multi-source BFS from all thieves fills thedistance tablethreshold = 2012012210211222Step 2 — keep only cells with dist >= 2 and check ifthe goal is reachableanswer = largest mid with a valid pathlo = 0, hi = 2 * n
First fill every cell with its distance to the closest thief, then test candidate safety values.
ComplexityTime O(n^2 log n)Space O(n^2)The multi-source BFS and each reachability check cost O(n^2), and binary search over the answer adds a factor of log n.

What Trips People Up in Real Interviews

1

Clarify what Manhattan distance means — |r1-r2| + |c1-c2|.

2

Confirm the grid is square (n x n) and values are non-negative.

3

Edge case: grid[0][0] has a thief — safety of any path is 0.

4

Discuss trade-offs between binary search + BFS vs. heap-based approach.

5

Be careful with the binary search bounds: low=0, high=2*n.

Solution Code

O(n^2 log n) time
def maximumSafenessFactor(grid):
    from collections import deque
    n = len(grid)
    dist = [[-1]*n for _ in range(n)]
    q = deque()
    for i in range(n):
        for j in range(n):
            if grid[i][j] == 1:
                dist[i][j] = 0
                q.append((i, j))
    while q:
        r, c = q.popleft()
        for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
            nr, nc = r+dr, c+dc
            if 0 <= nr < n and 0 <= nc < n and dist[nr][nc] == -1:
                dist[nr][nc] = dist[r][c] + 1
                q.append((nr, nc))
    def canReach(threshold):
        if dist[0][0] < threshold:
            return False
        visited = [[False]*n for _ in range(n)]
        stack = [(0, 0)]
        visited[0][0] = True
        while stack:
            r, c = stack.pop()
            if r == n-1 and c == n-1:
                return True
            for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
                nr, nc = r+dr, c+dc
                if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc] and dist[nr][nc] >= threshold:
                    visited[nr][nc] = True
                    stack.append((nr, nc))
        return False
    lo, hi = 0, 2 * n
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if canReach(mid):
            lo = mid
        else:
            hi = mid - 1
    return lo

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Find the Safest Path in a Grid problem?

You are given a 0-indexed 2D grid grid where grid[i][j] represents the number of thieves at that cell. The safety of a path from (0,0) to (n-1,n-1) is the minimum Manhattan distance from any cell on the path to any thief. Return the maximum possible safety value of any path from top-left to bottom-right.

How do you solve Find the Safest Path in a Grid?

The optimal approach runs in O(n^2 log n) time and O(n^2) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Find the Safest Path in a Grid?

Find the Safest Path in a Grid is asked at Uber. It is a medium difficulty problem.

What are common mistakes on Find the Safest Path in a Grid?
  • Clarify what Manhattan distance means — |r1-r2| + |c1-c2|.
  • Confirm the grid is square (n x n) and values are non-negative.
  • Edge case: grid[0][0] has a thief — safety of any path is 0.
  • Discuss trade-offs between binary search + BFS vs. heap-based approach.
  • Be careful with the binary search bounds: low=0, high=2*n.