#2812

Find the Safest Path in a Grid

Medium
ArrayBinary SearchBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixBreadth-First SearchBinary Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n² log n)
Space
O(n)
O(n²)
💡

Intuition

Time O(n² log n)Space O(n²)

The optimal solution combines BFS to calculate the minimum distance from each cell to the nearest thief and uses binary search to find the maximum safeness factor efficiently. This approach avoids exploring all paths explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform a multi-source BFS starting from all cells containing thieves to calculate the minimum distance to each cell in the grid.
  2. 2Step 2: Use binary search to find the maximum safeness factor that allows a valid path from (0, 0) to (n-1, n-1).
  3. 3Step 3: For each mid value in binary search, check if there's a valid path using BFS that maintains at least that safeness factor.
solution.py47 lines
1from collections import deque
2
3def maxSafenessFactor(grid):
4    n = len(grid)
5    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
6    distance = [[float('inf')] * n for _ in range(n)]
7    queue = deque()
8
9    for i in range(n):
10        for j in range(n):
11            if grid[i][j] == 1:
12                queue.append((i, j))
13                distance[i][j] = 0
14
15    while queue:
16        x, y = queue.popleft()
17        for dx, dy in directions:
18            nx, ny = x + dx, y + dy
19            if 0 <= nx < n and 0 <= ny < n and distance[nx][ny] == float('inf'):
20                distance[nx][ny] = distance[x][y] + 1
21                queue.append((nx, ny))
22
23    def canReach(safeness):
24        visited = set()
25        queue = deque([(0, 0)])
26        visited.add((0, 0))
27        while queue:
28            x, y = queue.popleft()
29            if x == n - 1 and y == n - 1:
30                return True
31            for dx, dy in directions:
32                nx, ny = x + dx, y + dy
33                if 0 <= nx < n and 0 <= ny < n and (nx, ny) not in visited:
34                    if distance[nx][ny] >= safeness:
35                        visited.add((nx, ny))
36                        queue.append((nx, ny))
37        return False
38
39    left, right = 0, n * 2
40    while left < right:
41        mid = (left + right + 1) // 2
42        if canReach(mid):
43            left = mid
44        else:
45            right = mid - 1
46
47    return left

Complexity note: The BFS runs in O(n²) to compute distances, and the binary search runs log(n²) times, leading to an overall complexity of O(n² log n). The space complexity is O(n²) due to the distance matrix.

  • 1Using BFS to calculate distances allows us to efficiently determine the safeness factor for paths.
  • 2Binary search helps in optimizing the search for the maximum safeness factor.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.