Program to find land with longest distance from water in Python

When given a binary matrix where 0 represents water and 1 represents land, we need to find the land cell with the longest Manhattan distance from any water cell. The Manhattan distance is the sum of absolute differences of coordinates.

So, if the input matrix is ?

1 1 1 1
1 1 0 1
1 1 1 1
0 0 1 1

Then the output will be 3, as the cell at [0,0] has a Manhattan distance of 3 from the nearest water.

Algorithm Approach

We'll use a multi-source BFS (Breadth-First Search) approach to solve this problem ?

  • Start BFS from all water cells (0s) simultaneously
  • Calculate distances to all land cells layer by layer
  • Return the maximum distance found

Step-by-Step Solution

The algorithm works as follows ?

  1. Handle edge cases (empty matrix or all water/all land)
  2. Initialize a distance matrix and queue with all water cell positions
  3. Use BFS to propagate distances from water cells to land cells
  4. Return the maximum distance found

Implementation

from collections import deque

class Solution:
    def solve(self, matrix):
        if not matrix:
            return 0
        
        R, C = len(matrix), len(matrix[0])
        distance = [[0] * C for _ in range(R)]
        
        # Queue with all water cells (0s)
        queue = deque((r, c) for r in range(R) for c in range(C) if not matrix[r][c])
        
        # If all water or all land, return -1
        if len(queue) in (0, R * C):
            return -1
        
        # BFS from all water cells
        while queue:
            r, c = queue.popleft()
            
            # Check all 4 directions
            for x, y in [(r - 1, c), (r + 1, c), (r, c + 1), (r, c - 1)]:
                if 0 <= x < R and 0 <= y < C and matrix[x][y]:
                    matrix[x][y] = 0  # Mark as visited
                    distance[x][y] = distance[r][c] + 1
                    queue.append((x, y))
        
        return max(max(row) for row in distance)

# Test the solution
solution = Solution()
matrix = [
    [1, 1, 1, 1],
    [1, 1, 0, 1],
    [1, 1, 1, 1],
    [0, 0, 1, 1]
]

result = solution.solve(matrix)
print(f"Maximum distance from water: {result}")
Maximum distance from water: 3

How It Works

The algorithm uses multi-source BFS starting from all water cells simultaneously. Here's the process ?

  1. Initialization: All water cells start with distance 0
  2. Layer 1: Adjacent land cells get distance 1
  3. Layer 2: Next adjacent land cells get distance 2
  4. Continue: Until all reachable land cells have distances

Visual Example

Original Matrix: 1 1 1 1 1 1 0 1 1 1 1 1 0 0 1 1 Distance Matrix: 3 2 1 2 2 1 0 1 1 1 1 2 0 0 1 2 Green = Land (1), Blue = Water (0) Distance colors: White = 0, Light Pink = 1, Pink = 2, Dark Pink = 3

Time and Space Complexity

  • Time Complexity: O(R × C), where R and C are matrix dimensions
  • Space Complexity: O(R × C) for the distance matrix and queue

Conclusion

This solution efficiently finds the land cell furthest from water using multi-source BFS. The algorithm starts from all water cells simultaneously and propagates distances outward, ensuring optimal results in linear time.

Updated on: 2026-03-25T13:30:44+05:30

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements