Approach
Breadth-first search
For Find the Safest Path in a Grid, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 64 lines of Python from the credited upstream file 2812.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def maximumSafenessFactor(self, grid: list[list[int]]) -> int:3 self.DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))4 n = len(grid)5 distToThief = self._getDistToThief(grid)6 7 def hasValidPath(safeness: int) -> bool:8 if distToThief[0][0] < safeness:9 return False10 11 q = collections.deque([(0, 0)])12 seen = {(0, 0)}13 14 while q:15 i, j = q.popleft()16 if distToThief[i][j] < safeness:17 continue18 if i == n - 1 and j == n - 1:19 return True20 for dx, dy in self.DIRS:21 x = i + dx22 y = j + dy23 if x < 0 or x == n or y < 0 or y == n:24 continue25 if (x, y) in seen:26 continue27 q.append((x, y))28 seen.add((x, y))29 30 return False31 32 return bisect.bisect_left(range(n * 2), True,33 key=lambda m: not hasValidPath(m)) - 134 35 def _getDistToThief(self, grid: list[list[int]]) -> list[list[int]]:36 n = len(grid)37 distToThief = [[0] * n for _ in range(n)]38 q = collections.deque()39 seen = set()40 41 for i in range(n):42 for j in range(n):43 if grid[i][j] == 1:44 q.append((i, j))45 seen.add((i, j))46 47 dist = 048 while q:49 for _ in range(len(q)):50 i, j = q.popleft()51 distToThief[i][j] = dist52 for dx, dy in self.DIRS:53 x = i + dx54 y = j + dy55 if x < 0 or x == n or y < 0 or y == n:56 continue57 if (x, y) in seen:58 continue59 q.append((x, y))60 seen.add((x, y))61 dist += 162 63 return distToThief64