All problems
1031MediumArrayDynamic ProgrammingBreadth-First SearchMatrix

The Most Sheltered Berth

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1162As Far from Land as Possible

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A square chart chart marks each cell 1 for land or 0 for water. A step goes between cells sharing an edge, over land or water alike, and the distance between two cells is the fewest steps between them.

Return the largest distance any water cell sits from its nearest land cell. When the chart is all land or all water, return -1.

Examples

Example 1

Input
chart = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Output
2

The single land cell sits in the middle. Each corner is two steps from it, one across and one down, and nothing on the chart is farther.

Example 2

Input
chart = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Output
-1

There is no water anywhere, so there is no berth to measure.

Example 3

Input
chart = [[0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Output
6

The only land sits in the top-right corner, so the bottom-left corner is the farthest berth, three steps down and three across.

Constraints

  • 1 <= chart.length <= 100
  • Every row of chart is as long as the chart is tall.
  • 0 <= chart[i][j] <= 1

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def max_distance(chart: list[list[int]]) -> int:
Java
public int maxDistance(int[][] chart)
September 7
Apply