# Program to find area of largest island in a matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix. Here 1 represents land and 0 represents water, And an island is a group of 1s that are neighboring whose perimeter is surrounded by water. We can assume that the edges of the matrix are surrounded by water. We have to find the area of the largest island in matrix.

So, if the input is like

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

then the output will be 6.

To solve this, we will follow these steps −

• Define a function dfs() . This will take matrix, r, c
• total := total + 1
• matrix[r, c] := 0
• if r - 1 >= 0 and matrix[r - 1, c] is same as 1, then
• dfs(matrix, r - 1, c)
• if c - 1 >= 0 and matrix[r, c - 1] is same as 1, then
• dfs(matrix, r, c - 1)
• if r + 1 < r_len and matrix[r + 1, c] is same as 1, then
• dfs(matrix, r + 1, c)
• if c + 1 < c_len and matrix[r, c + 1] is same as 1, then
• dfs(matrix, r, c + 1)
• From the main method, do the following −
• r_len := row count of matrix
• c_len := column count of matrix
• max_island := 0
• for r in range 0 to r_len - 1, do
• for c in range 0 to c_len - 1, do
• if matrix[r, c] is same as 1, then
• total := 0
• dfs(matrix, r, c)
• max_island := maximum of max_island, total
• return max_island

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, matrix):
self.r_len = len(matrix)
self.c_len = len(matrix[0])
max_island = 0
for r in range(self.r_len):
for c in range(self.c_len):
if matrix[r][c] == 1:
self.total = 0
self.dfs(matrix, r, c)
max_island = max(max_island, self.total)
return max_island
def dfs(self, matrix, r, c):
self.total += 1
matrix[r][c] = 0
if r - 1 >= 0 and matrix[r - 1][c] == 1:
self.dfs(matrix, r - 1, c)
if c - 1 >= 0 and matrix[r][c - 1] == 1:
self.dfs(matrix, r, c - 1)
if r + 1 < self.r_len and matrix[r + 1][c] == 1:
self.dfs(matrix, r + 1, c)
if c + 1 < self.c_len and matrix[r][c + 1] == 1:
self.dfs(matrix, r, c + 1)
ob = Solution()
matrix = [ [0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0] ]
print(ob.solve(matrix))

## Input

matrix = [
[0, 0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 0] ]

## Output

6
Updated on 19-Nov-2020 06:44:56