Problem Description
Given an n x n grid where cells contain either 0 (empty) or 1 (a thief), you must find a path from cell (0, 0) to (n - 1, n - 1). The safeness factor of a path is defined as the minimum Manhattan distance from any cell in the path to any thief in the grid. The goal is to maximize this safeness factor over all possible valid paths (moving up, down, left, or right).
Key Insights
- Compute for each cell the Manhattan distance to its nearest thief. This is efficiently done via multi-source BFS starting from every cell containing a thief.
- With precomputed distances, the problem becomes one of finding a path from the start to the end such that every visited cell has a distance (safeness factor) at least X.
- Use binary search (or a Dijkstra-style max-min path algorithm) to find the maximum possible X such that a valid path exists.
- During the binary search, perform a BFS or DFS from (0, 0) using only cells whose distance from a thief is >= candidate value X.
Space and Time Complexity
Time Complexity: O(n^2 log(n))
Space Complexity: O(n^2)
Solution
- Use multi-source BFS to compute a distance matrix (dist) where dist[r][c] is the Manhattan distance from cell (r, c) to the nearest thief.
- Perform a binary search on the possible safeness factor X. For each candidate X:
- Check if (0, 0) itself has distance >= X. If yes, do a BFS/DFS from (0,0) considering only cells with distance >= X.
- If you can reach (n - 1, n - 1), candidate X is feasible.
- The binary search finds the maximum X for which a valid path exists.
Data Structures and Techniques:
- Queue for multi-source BFS for computing distance.
- Another queue (or stack) for the connectivity check during binary search.
- Binary search to efficiently pinpoint the maximum safeness factor.
Important considerations:
- The multi-source BFS starts with all thief cells; their initial distance is 0.
- During connectivity check, boundary conditions and proper marking of visited cells are essential.
- The grid size (up to 400 x 400) requires efficient O(n^2) traversals and careful management of recursion/iteration.