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.
Input: grid =[[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,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, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
We can use BFS to calculate the safeness factor for each cell in the grid, as BFS goes like a wave wise or level by level. We can create distances matrix for eg. 3 like this:
Once, we have distances matrix, now we have to find path such that it’s as far as possible from thief. For this we can simply choose to go at max distance cell starting from {0,0} using max heap. We can easily see, the nearest distance in this path from thief is 2. So, when adding the value in max heap, we add smallest safeness factor we have encountered so far. Once we have reach our destination, we return the smallest safeness factor.
⏰ Time complexity: O(n^2 log n^2) - We loop on grid once to fill in queue and initial values in distances matrix - this takes O(n^2). Then we perform multi-source BFS with O(n^2) again. Then we use maxHeap to find the path search, and at a time heap contains n^2 element, and searching those elements take O(n^2)log(n^2) time, which will be O(n^2)