662. Farthest From Land

Medium3.5 points estimatedMatrixGraphBreadth-First Search3 hints

A satellite map is stored in the grid grid, where 1 marks land and 0 marks open sea. For a sea cell, its shore distance is the smallest Manhattan distance |r1 - r2| + |c1 - c2| from it to any land cell. Choose the sea cell whose shore distance is as large as possible and return that distance.

If the map contains no land at all, or no sea at all, there is nothing meaningful to measure and you must return -1. The map can be several hundred cells on a side, so comparing every sea cell against every land cell is too slow; your solution should run in time proportional to the number of cells.

Example 1

Input:
grid = [[1,0,0],[0,0,0],[0,0,1]]
Output:
2
Explanation:

Land sits in two opposite corners; the sea cells (0,2), (1,1) and (2,0) are each 2 steps from the nearest land, and no sea cell is farther, so the answer is 2.

Example 2

Input:
grid = [[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]]
Output:
4
Explanation:

A single land cell at (1,1); the sea corner (3,3) is 2 + 2 = 4 steps away, the maximum.

Example 3

Input:
grid = [[0,0],[0,0]]
Output:
-1
Explanation:

There is no land, so the answer is -1.

Constraints

1 ≤ rows, cols ≤ 400

each cell is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(rows*cols)
Space
O(rows*cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…