1066. As Far from Land as Possible

MediumGraphsGridBFSGraph

Given an n x n grid of 0s (water) and 1s (land), find the water cell whose distance to the nearest land cell is maximized, and return that distance (Manhattan, moving 4-directionally). Return -1 if the grid is all land or all water. The input is JSON {grid}.

Input: JSON {grid}.

Output: Integer — the maximum distance, or -1.

Examples

Example 1
Input: {"grid":[[1,0,1],[0,0,0],[1,0,1]]}
Output: 2
Explanation: The center is distance 2 from land.
Example 2
Input: {"grid":[[1,0,0],[0,0,0],[0,0,0]]}
Output: 4
Explanation: The far corner is distance 4.
Example 3
Input: {"grid":[[1]]}
Output: -1
Explanation: All land.

Constraints

Asked by

AmazonMicrosoftGoogle
Solve this problem in the editor →