# Program to find land with longest distance from water in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a binary matrix where, 0 represents water and 1 represents land. Now we have to find the land which has the longest Manhattan distance from water and finally return the distance.

So, if the input is like

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

then the output will be 3, as [0,0] cell has Manhattan distance of 3 from water.

To solve this, we will follow these steps −

• if A is empty, then
• return 0
• R := row count of matrix, C := column count of matrix
• distance := a matrix of order R x C and fill with 0
• q := a double ended queue with some pairs (r, c) where r and c are row and column index of matrix where matrix[r, c] is 0
• if size of q is wither 0 or R * C, then
• return -1
• while q is not empty, do
• (r, c) := left element of q, then remove from q
• for each pair (x, y) in [(r - 1, c) ,(r + 1, c) ,(r, c + 1) ,(r, c - 1) ], do
• if x and y are in range of matrix and A[x, y] is 1, then
• A[x, y] := 0
• distance[x, y] := distance[r, c] + 1
• insert (x, y) at the end of q
• res := a list of containing maximum element of each rows
• return maximum of res

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

from collections import deque
class Solution:
def solve(self, A):
if not A:
return 0
R, C = len(A), len(A[0])
distance = [[0] * C for _ in range(R)]
q = deque((r, c) for r in range(R) for c in range(C) if not A[r][c])
if len(q) in (0, R * C):
return -1
while q:
r, c = q.popleft()
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 A[x][y]:
A[x][y] = 0
distance[x][y] = distance[r][c] + 1
q.append((x, y))
return max(max(row) for row in distance)
ob = Solution()
matrix = [
[1, 1, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 1],
[0, 0, 1, 1]
]
print(ob.solve(matrix))

## Input

[
[1, 1, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 1],
[0, 0, 1, 1]
]

## Output

3
Updated on 12-Dec-2020 09:25:00