Find the Safest Path in a Grid - Complete Solution Guide
Find the Safest Path in a Grid is LeetCode problem 2812, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given a 0-indexed 2D matrix grid of size n x n , where (r, c) represents: A cell containing a thief if grid[r][c] = 1 An empty cell if grid[r][c] = 0 You 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 ce
Detailed Explanation
The problem asks us to find the maximum 'safeness factor' among all possible paths from the top-left cell (0, 0) to the bottom-right cell (n-1, n-1) in a given n x n grid. The grid contains information about the presence of 'thieves' (represented by 1) and empty cells (represented by 0). The 'safeness factor' of a path is defined as the minimum Manhattan distance from any cell in the path to the nearest thief. The goal is to return the largest possible safeness factor among all valid paths from the start to the end.
Solution Approach
The solution uses a combination of BFS and Binary Search. First, it calculates the distance of each cell in the grid to the nearest thief using BFS. This is stored in a `dist_grid`. Then, it applies Binary Search on the possible safeness factors (from 0 to 2*n, the maximum possible Manhattan distance in the grid). For each potential safeness factor during the Binary Search, another BFS is employed to check if a path exists from (0, 0) to (n-1, n-1) such that all cells on the path have a distance to the nearest thief greater than or equal to the current safeness factor. If such a path exists, we try a higher safeness factor; otherwise, we try a lower one. The final valid safeness factor is the answer.
Step-by-Step Algorithm
- Step 1: **Calculate Distance to Nearest Thief:** Perform a BFS starting from all cells containing thieves (grid[r][c] == 1). For each cell, store the minimum Manhattan distance to a thief in `dist_grid`.
- Step 2: **Binary Search for Safeness Factor:** Initialize `low` to 0 and `high` to 2*n (maximum possible Manhattan distance). Perform a binary search between `low` and `high` to find the optimal safeness factor.
- Step 3: **Check if Path Exists for a Given Safeness Factor:** For each mid-value (potential safeness factor) in the binary search, perform another BFS. This BFS starts at (0, 0) and only explores neighboring cells (r, c) in the grid if `dist_grid[r][c]` is greater than or equal to the potential safeness factor. If this BFS reaches (n-1, n-1), it means a path exists with that safeness factor, and we can try a higher safeness factor. Otherwise, no such path exists, and we need to try a lower safeness factor.
- Step 4: **Update Binary Search Range:** Based on whether a path was found in Step 3, update the `low` or `high` pointer for the binary search. If a path was found, increase `low` to `mid + 1`. If no path was found, decrease `high` to `mid - 1`.
- Step 5: **Return Result:** The final answer is the largest safeness factor for which a path exists, which is represented by the variable `ans` after the binary search completes.
Key Insights
- Insight 1: We need to calculate the Manhattan distance of each cell to the nearest thief efficiently. Breadth-First Search (BFS) is suitable for this.
- Insight 2: Instead of directly searching for the path with the maximum safeness factor, we can use Binary Search. This allows us to check if a path with a given safeness factor exists.
- Insight 3: To check if a path with a given safeness factor exists, we can use BFS again, but only explore cells whose distance to the nearest thief is greater than or equal to the given safeness factor.
Complexity Analysis
Time Complexity: O(n^2 * log(n))
Space Complexity: O(n^2)
Topics
This problem involves: Array, Binary Search, Breadth-First Search, Union Find, Heap (Priority Queue), Matrix.
Companies
Asked at: IMC, Wells Fargo.