As Far from Land as Possible

Medium Topics Company Tags

The square grid uses 0 for water and 1 for land. For each water cell, measure the distance to its nearest land cell using abs(row1 - row2) + abs(column1 - column2). Return the largest of these nearest-land distances. If there is no water or there is no land, return -1.

Example 1:

As Far from Land as Possible, example 1: illustration of the example

Input: grid = [[1,0],[0,0]]

Output: 2

Explanation: The only land is at (0,0). Water at (1,1) is farthest from it, with distance |1-0| + |1-0| = 2.

Example 2:

As Far from Land as Possible, example 2: illustration of the example

Input: grid = [[1,1],[1,1]]

Output: -1

Explanation: There is no water cell to choose, so the result is -1.

Example 3:

As Far from Land as Possible, example 3: illustration of the example

Input: grid = [[0,0],[0,0]]

Output: -1

Explanation: There is no land cell from which to measure distance, so the result is -1.

Constraints:

  • 1 <= grid.length <= 100
  • Every row has grid.length entries.
  • Every entry is either 0 or 1.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.