Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 ?
- Handle edge cases (empty matrix or all water/all land)
- Initialize a distance matrix and queue with all water cell positions
- Use BFS to propagate distances from water cells to land cells
- 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 ?
- Initialization: All water cells start with distance 0
- Layer 1: Adjacent land cells get distance 1
- Layer 2: Next adjacent land cells get distance 2
- Continue: Until all reachable land cells have distances
Visual Example
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.
