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

Suppose we have a binary matrix where 1 represents land and 0 represents water. An island is a group of connected 1s whose perimeter is surrounded by water. We can assume that the edges of the matrix are surrounded by water. We need to find the area of the largest island in the matrix.

So, if the input matrix 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, as the largest island has 6 connected land cells.

Algorithm

To solve this problem, we use Depth-First Search (DFS) to explore each island and calculate its area ?

  • Iterate through each cell in the matrix
  • When we find a land cell (value 1), start DFS to count all connected land cells
  • Mark visited cells as 0 to avoid counting them again
  • Keep track of the maximum island area found

Using DFS Approach

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):
        # Count current cell and mark as visited
        self.total += 1
        matrix[r][c] = 0
        
        # Check all 4 directions (up, left, down, right)
        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)

# Test the solution
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("Largest island area:", ob.solve(matrix))
Largest island area: 6

How It Works

The algorithm works by ?

  • Matrix traversal: We iterate through every cell in the matrix
  • Island detection: When we find a land cell (1), we start exploring the entire island
  • DFS exploration: The DFS function recursively visits all connected land cells in 4 directions
  • Area calculation: Each visited cell increments the total counter
  • Marking visited: We set visited cells to 0 to prevent double-counting

Alternative Approach Using BFS

from collections import deque

def largest_island_bfs(matrix):
    if not matrix or not matrix[0]:
        return 0
    
    rows, cols = len(matrix), len(matrix[0])
    max_area = 0
    
    def bfs(start_r, start_c):
        queue = deque([(start_r, start_c)])
        matrix[start_r][start_c] = 0
        area = 0
        
        while queue:
            r, c = queue.popleft()
            area += 1
            
            # Check all 4 directions
            for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] == 1:
                    matrix[nr][nc] = 0
                    queue.append((nr, nc))
        
        return area
    
    for r in range(rows):
        for c in range(cols):
            if matrix[r][c] == 1:
                island_area = bfs(r, c)
                max_area = max(max_area, island_area)
    
    return max_area

# Test BFS approach
matrix2 = [
    [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("Using BFS:", largest_island_bfs(matrix2))
Using BFS: 6

Time and Space Complexity

  • Time Complexity: O(m × n) where m and n are matrix dimensions
  • Space Complexity: O(m × n) in worst case due to recursion stack depth

Conclusion

Both DFS and BFS approaches effectively solve the largest island problem by exploring connected land cells. DFS is simpler to implement recursively, while BFS uses iterative approach with a queue. The key insight is marking visited cells to avoid double-counting.

Updated on: 2026-03-25T12:31:10+05:30

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements