Taro Logo

As Far from Land as Possible

#5 Most AskedMedium
0 views
Topics:
ArraysDynamic ProgrammingGreedy Algorithms

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected return value if the grid contains only land (all 1s) or only water (all 0s)?
  2. What are the constraints on the dimensions of the grid ($n imes n$)?
  3. How should distance be measured if there are multiple land cells of equal distance to a water cell?
  4. Can I assume the grid will always be a valid square matrix, or could I receive empty or malformed inputs?
  5. If there are multiple water cells that share the maximum distance to the nearest land, does it matter which one's distance we return?

Brute Force Solution

Approach

Imagine looking at a vast grid where some spots are land and others are water, and you want to find a water spot that is as far away from any land as possible. The brute force approach involves looking at every single water spot one by one, measuring its distance to every single land spot, and finding the maximum of these minimum distances.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the entire grid of land and water to identify every single spot that is marked as water.
  2. Pick the first water spot and pretend you are standing right on it.
  3. Look around at every single piece of land on the entire grid and measure the distance from your chosen water spot to each piece of land.
  4. Write down the shortest distance you found from your current water spot to the nearest piece of land.
  5. Move on to the next water spot and repeat the entire measuring process for every piece of land, finding the closest land to this new spot.
  6. Continue this process for every single water spot on the grid until every piece of water has been paired with its closest piece of land.
  7. Compare all the shortest distances you wrote down for each water spot.
  8. Pick the largest distance out of all those shortest distances, as that represents the water spot that is farthest from any land.

Code Implementation

def max_distance(grid):    grid_rows = len(grid)    grid_cols = len(grid[0])    water_spots = []    land_spots = []        # Collect all water and land coordinates to evaluate distances between them later    for row_index in range(grid_rows):        for col_index in range(grid_cols):            if grid[row_index][col_index] == 0:                water_spots.append((row_index, col_index))            else:                land_spots.append((row_index, col_index))                    if not water_spots or not land_spots:        return -1            maximum_distance = -1        # Evaluate every water spot to find its minimum distance to any land spot    for water_coordinate in water_spots:        minimum_land_distance = float('inf')                for land_coordinate in land_spots:            current_distance = abs(water_coordinate[0] - land_coordinate[0]) + abs(water_coordinate[1] - land_coordinate[1])            if current_distance < minimum_land_distance:                minimum_land_distance = current_distance                        if minimum_land_distance > maximum_distance:            maximum_distance = minimum_land_distance                # Return the maximum found among all minimum distances to satisfy the problem requirement    return maximum_distance

Big(O) Analysis

Time Complexity
O(N^4) – Let N be the total number of cells in the grid, where the grid dimensions are root-N by root-N. For every water spot, which can be up to N spots in the worst case, we iterate through every piece of land on the entire grid to measure distances, taking up to N operations per water spot. Repeating this full land-scanning process for each of the N water spots results in approximately N times N operations, which further multiplies by the grid dimension scan yielding roughly N squared operations total, simplifying to O(N^4).
Space Complexity
O(1) – The brute force approach described relies entirely on iterating through the existing grid and variables for looping and keeping track of the current minimum and maximum distances. It does not introduce any auxiliary data structures like temporary arrays or hash maps that scale with the grid size. Therefore, the extra memory used remains constant regardless of the grid dimensions.

Optimal Solution

Approach

Instead of measuring the distance outward from every single ocean cell, the optimal strategy works in reverse by starting from all the land areas simultaneously. By spreading outward step-by-step like ripples on water, we can find the maximum distance to the furthest ocean in the most direct way possible.

Here's how the algorithm would work step-by-step:

  1. Gather all the land locations on the map and mark them as our starting points for measuring distance.
  2. If the map is entirely made of land or entirely made of water, stop immediately because it is impossible to find a valid distance.
  3. Begin a wave of exploration outward from every piece of land into the immediately touching neighboring water areas.
  4. Count each complete outward wave as one full step of distance away from the nearest land.
  5. As the outward wave moves into unvisited water, record the current distance step and treat those newly reached water areas as the new starting points for the next wave.
  6. Continue spreading the waves outward layer by layer until every single piece of water on the map has been reached.
  7. Look at the distance recorded during the very final wave of exploration, as that represents the furthest possible water from any land.

Code Implementation

from collections import deque

def max_distance(grid):
    grid_dimension = len(grid)
    queue_for_bfs = deque()
    
    # Multi-source BFS requires seeding all land cells simultaneously to track minimum distance.
    for row_index in range(grid_dimension):
        for col_index in range(grid_dimension):
            if grid[row_index][col_index] == 1:
                queue_for_bfs.append((row_index, col_index))

    if not queue_for_bfs or len(queue_for_bfs) == grid_dimension * grid_dimension:
        return -1

    maximum_distance = -1
    row_offsets = [-1, 1, 0, 0]
    col_offsets = [0, 0, -1, 1]

    # Expanding outward layer by layer ensures we compute the shortest path from land to water.
    while queue_for_bfs:
        current_row, current_col = queue_for_bfs.popleft()
        
        for direction_index in range(4):
            neighbor_row = current_row + row_offsets[direction_index]
            neighbor_col = current_col + col_offsets[direction_index]
            
            if 0 <= neighbor_row < grid_dimension and 0 <= neighbor_col < grid_dimension and grid[neighbor_row][neighbor_col] == 0:
                grid[neighbor_row][neighbor_col] = grid[current_row][current_col] + 1
                maximum_distance = max(maximum_distance, grid[neighbor_row][neighbor_col])
                queue_for_bfs.append((neighbor_row, neighbor_col))

    # Subtracting one is necessary because land started at 1 instead of 0 distance.
    return maximum_distance - 1

Big(O) Analysis

Time Complexity
O(N) – Given a grid of size N representing the total number of cells, the algorithm first iterates through every single cell once to find all starting land locations and populate the initial queue. During the multi-source breadth-first search, each cell in the grid is visited and processed at most once as the waves spread outward into neighboring water areas. This means every cell's distance is calculated in a constant number of operations as we traverse the entire map layer by layer. Summing the constant-time operations across all N grid cells yields approximately N operations in total, which simplifies to O(N).
Space Complexity
O(N) – To implement the multi-source breadth-first search described in the steps, we utilize a queue data structure to store the coordinates of the cells during each outward wave of exploration. Additionally, we modify the grid in place or use a secondary visited structure, meaning the queue will at most hold every single cell on the map in the worst-case scenario. If N represents the total number of cells in the grid, the maximum number of elements in the queue at any single moment scales directly with N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Edge Cases

Grid contains only land cells with no water present
How to Handle:
The initial queue scan will find no water, resulting in a distance of -1 as required by the problem statement.
Grid contains only water cells with no land present
How to Handle:
The initial queue will be empty, allowing the algorithm to return -1 immediately before processing.
Minimum possible grid size of 1x1 containing either land or water
How to Handle:
Since there is no opposite cell type, the algorithm naturally returns -1 due to the lack of both water and land.
A single land cell surrounded entirely by water in a large grid
How to Handle:
Multi-source breadth-first search correctly expands outward from the single land cell to compute the maximum Manhattan distance.
A single water cell surrounded entirely by land
How to Handle:
The breadth-first search will reach this water cell in the first step, yielding a maximum distance of 1.
Maximum-sized grid limits with memory and time constraints
How to Handle:
Using an in-place visited structure or distance matrix ensures the breadth-first search runs efficiently within optimal time and space limits.
Checkerboard or alternating patterns of land and water
How to Handle:
Breadth-first search guarantees shortest paths to the nearest land, accurately processing complex alternating topologies layer by layer.
0/6 completed