You are given a 0-indexed 2D matrix grid of size n x n, where (r, c) represents:
grid[r][c] = 1grid[r][c] = 0You are initially positioned at cell (0, 0). In one move, you can move to any adjacent cell in the grid, including cells containing thieves.
The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid.
Return the maximum safeness factor of all paths leading to cell (n - 1, n - 1).
An adjacent cell of cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) and (r - 1, c) if it exists.
The Manhattan distance between two cells (a, b) and (x, y) is equal to |a - x| + |b - y|, where |val| denotes the absolute value of val.
Input: grid = [[1,0,0],[0,0,0],[0,0,1]]
Output: 0
Explanation: All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
Input: grid = [[0,0,1],[0,0,0],[0,0,0]]
Output: 2
Explanation: The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
1 <= grid.length == n <= 400grid[i].length == ngrid[i][j] is either 0 or 1.The most naive way to solve this is to explore every possible path from (0,0) to (n-1,n-1) using Depth-First Search (DFS).
Why we don't do this (and why we use BFS instead): Computing the distance to all thieves for every single cell is extremely redundant and slow. Additionally, there are exponentially many paths in a grid. By using Multi-Source BFS, we can precalculate the minimum distance to the nearest thief for every cell globally in just O(n²) time. Then, Dijkstra allows us to greedily pick the safest route without exhaustively exploring all paths!
The problem asks us to find a path where the minimum distance to a thief is maximized. This is a classic "maximize the minimum" path problem.
minDist for every cell in O(n²) time.min(current_safeness, minDist[neighbor]).(n-1, n-1) from the Max-Heap, we are guaranteed to have found the path with the maximum possible safeness factor!
Discussion
…