Skip to main content

As Far from Land as Possible - Solution & Explanation

MediumArrayDynamic ProgrammingBreadth-First SearchMatrix14 min readAsked at: Amazon, Microsoft, Google +4
Practice this problem

Problem Statement

Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.

The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.

 

Example 1:

Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.

Example 2:

Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.

 

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1

Approach Overview

Problem Overview: You get an n x n grid where 1 represents land and 0 represents water. The goal is to find the water cell whose Manhattan distance to the nearest land cell is maximized. If the grid contains only land or only water, return -1.

Approach 1: Brute Force Distance Search (O(n^4) time, O(1) space)

Iterate through every water cell and compute its distance to every land cell. Track the minimum distance to land for that water cell, then update the global maximum. The Manhattan distance between two cells (r1,c1) and (r2,c2) is |r1-r2| + |c1-c2|. This approach performs two nested loops for selecting a water cell and two more loops for scanning all land cells, resulting in O(n^4) time. The implementation is straightforward but extremely slow for larger grids. It mainly helps demonstrate the core idea: each water cell cares about the closest land.

Approach 2: Multi-Source Breadth-First Search (BFS) (O(n^2) time, O(n^2) space)

The optimal solution treats all land cells as starting points of a Breadth-First Search. Insert every land cell into a queue and expand outward simultaneously. Each BFS layer represents moving one step farther away from land. As the search spreads through neighboring cells (up, down, left, right), it converts water cells into visited nodes and pushes them into the queue. The last layer processed corresponds to the water cells farthest from any land.

This works because BFS always processes nodes in increasing distance order. Starting from all land cells guarantees that the first time a water cell is reached is the shortest distance to land. Track the number of BFS levels processed until the queue is empty. That level count becomes the answer.

The grid itself can act as the visited structure by marking visited water cells as land or another value. Each cell is processed at most once, giving O(n^2) time complexity. The queue may store up to all cells in the grid, so space complexity is also O(n^2). This pattern appears frequently in matrix problems where distances expand from multiple sources.

Approach 3: Dynamic Programming Distance Propagation (O(n^2) time, O(n^2) space)

A distance transform technique can also solve the problem using dynamic programming. Initialize distances as 0 for land and a large value for water. Perform two passes across the grid: top-left to bottom-right and bottom-right to top-left. Each pass relaxes distances using neighbors. This gradually propagates the shortest distance to land across the grid. After computing distances, scan water cells and return the maximum value. The approach is efficient but less intuitive in interviews compared to BFS.

Recommended for interviews: Multi-source BFS is the expected solution. It directly models distance expansion from all land cells and runs in optimal O(n^2) time. Interviewers usually want to see recognition of the multi-source BFS pattern in array grid problems. Showing the brute-force idea first demonstrates understanding of the distance definition, while the BFS optimization demonstrates algorithmic maturity.

Approach 1: Breadth-First Search (BFS) Approach

This approach uses BFS starting from all land cells simultaneously. We can think of the lands spreading out like waves in unison into the water cells, each wave representing a unit of distance. This helps us efficiently compute the farthest distance of a water cell from land.

The function uses a queue to implement BFS starting from all land cells. The queue holds the coordinates of the cells to be processed next. It explores all grid cells using BFS and calculates the maximum distance from the nearest land cell to a water cell.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

The time complexity is O(n2), where n is the dimension of the grid, as each cell is visited once. The space complexity is also O(n2) due to the queue that can store all cells in the grid.

Try this approach in the editor →

Approach 2: BFS

We can add all land cells to the queue q. If the queue is empty, or the number of elements in the queue equals the number of cells in the grid, it means that the grid contains only land or ocean, so return -1.

Otherwise, we start BFS from the land cells. Define the initial step count ans=-1.

In each round of search, we spread all cells in the queue in four directions. If a cell is an ocean cell, we mark it as a land cell and add it to the queue. After a round of spreading, we increase the step count by 1. Repeat this process until the queue is empty.

Finally, we return the step count ans.

The time complexity is O(n^2), and the space complexity is O(n^2). Here, n is the side length of the grid.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Breadth-First Search (BFS) Approach

The time complexity is O(n2), where n is the dimension of the grid, as each cell is visited once. The space complexity is also O(n2) due to the queue that can store all cells in the grid.

BFS—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Distance CheckO(n^4)O(1)Understanding the distance definition or very small grids
Multi-Source BFSO(n^2)O(n^2)Optimal solution for grid distance problems and interview settings
Dynamic Programming Distance TransformO(n^2)O(n^2)When avoiding BFS queues or applying matrix DP distance propagation

Video Solution

As Far from Land as Possible - Leetcode 1162 - Python • NeetCodeIO • 13,277 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is As Far from Land as Possible easy or hard?
As Far from Land as Possible is rated Medium on LeetCode. The difficulty comes from recognizing that the problem requires multi-source BFS rather than running BFS from each water cell. Once that pattern is identified, the implementation is straightforward.
As Far from Land as Possible Python/Java solution
Most implementations follow the same multi-source BFS template. Initialize a queue with all land cells, perform BFS expansion in four directions, and track levels until no more water cells remain. The logic translates directly across Python, Java, C++, JavaScript, C#, and C with similar O(n^2) complexity.
How to solve As Far from Land as Possible in O(n^2)?
Push all land cells into a queue and run a multi-source BFS. Expand in four directions and mark visited water cells as you go. The BFS depth represents distance from land, so the final level reached before the queue empties is the maximum water distance. Since each cell is processed once, the algorithm runs in O(n^2).
What is the best approach for As Far from Land as Possible?
The best approach is multi-source Breadth-First Search (BFS). Start BFS simultaneously from every land cell and expand outward into water cells. Each BFS layer represents increasing Manhattan distance from land, and the last processed layer gives the maximum distance. This runs in O(n^2) time and O(n^2) space.
Is As Far from Land as Possible asked at Google/Amazon/Meta?
Grid BFS problems similar to this appear frequently in interviews at companies like Amazon, Google, and Meta. The key skill tested is recognizing multi-source BFS patterns in matrix problems. Variations also appear in shortest path and distance-to-nearest problems.
What data structure is used in As Far from Land as Possible?
The core data structure is a queue used for Breadth-First Search. The grid acts as both the input and a visited structure by marking processed water cells. The algorithm also relies on simple array traversal and directional offsets to explore neighbors in the matrix.
What is the time complexity of As Far from Land as Possible?
The optimal multi-source BFS solution runs in O(n^2) time because each grid cell is visited at most once. Space complexity is also O(n^2) due to the queue and visited tracking. A naive brute-force method that checks every water cell against every land cell can take up to O(n^4) time.

Ready to solve this problem?

Practice As Far from Land as Possible with our built-in code editor and test cases.

Practice on FleetCode