Leetcode 1162: As Far from Land as Possible

grid47
grid47
Exploring patterns and algorithms
Jul 13, 2024 7 min read

Given a square grid of size n x n containing only 0s (water) and 1s (land), find the water cell that is farthest from any land cell based on Manhattan distance, and return that distance. If the grid has no water or no land, return -1.
Problem
Approach
Steps
Complexity
Input: A 2D grid of size n x n where each cell contains either 0 (water) or 1 (land).
Example: grid = [[1,0,1],[0,0,0],[1,0,1]]
Constraints:
• n == grid.length
• n == grid[i].length
• 1 <= n <= 100
• grid[i][j] is either 0 or 1
Output: An integer representing the maximum Manhattan distance from a water cell to the nearest land cell. Return -1 if no valid configuration exists.
Example: Output: 2
Constraints:
Goal: Calculate the maximum Manhattan distance of a water cell to the nearest land cell.
Steps:
• Initialize a queue to store land cells' coordinates.
• Mark water cells with -1 to differentiate unvisited cells.
• Perform a breadth-first search (BFS) starting from all land cells simultaneously.
• Update water cells with their distance to the nearest land cell.
• Keep track of the maximum distance during the BFS.
Goal: Ensure efficient computation for grids up to size 100x100.
Steps:
• Handle edge cases such as grids with no water or no land.
• Avoid out-of-bounds access during BFS.
Assumptions:
• Grid dimensions are always square.
• Input grid contains at least one water or one land cell.
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Explanation: The cell (2, 2) is the farthest from all land cells with a distance of 4.

Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Explanation: No water exists, so the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus