642. As Far from Land as Possible

MediumStackQueueBFSGrid

Given an n x n grid of 0s (water) and 1s (land), find the water cell whose distance to the nearest land is maximized, and return that distance (Manhattan). 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.
Example 3
Input: {"grid":[[0,0,0],[0,0,0]]}
Output: -1
Explanation: No land.

Constraints

Asked by

AmazonMicrosoftGoogle
Solve this problem in the editor →