1162. As Far from Land as Possible

Given an `n x n` grid containing 0 (water) and 1 (land), find the maximum distance from any water cell to the nearest land cell (4-directional). Return -1 if all land or all water. Use multi-source BFS from all lands.

Input Format

2D list of 0/1 ints.

Output Format

Max distance int or -1.

Constraints

  • n ≤ 100; grid values 0/1.

Examples

Example 1:

Input:

grid = [[1,0,1],[0,0,0],[1,0,1]]

Output:

2

Explanation:

Max distance is 2.

Loading...
1162. As Far from Land as Possible - Matrix