algoadvance

Given a binary matrix grid where 0 represents water and 1 represents land, you need to find the maximum area of an island in the matrix. An island is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.

Clarifying Questions:

  1. Input Specifications:
    • Is the input always a valid 2D binary matrix?
    • What are the maximum dimensions of the grid?
  2. Output Specifications:
    • Should the function return the size of the largest island found in the grid?

For this problem, let’s consider the following assumptions:

Strategy:

We’ll use Depth-First Search (DFS) to explore the grid. The main idea is:

  1. Traverse each cell in the grid.
  2. When we encounter a 1 (land), we initiate a DFS to compute the area of the island, marking cells as visited by changing them to 0 (water) to avoid recounting.
  3. Track the maximum area encountered during the traversal.

Code:

Here’s the implementation of the strategy described above.

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return 0

        max_area = 0
        rows, cols = len(grid), len(grid[0])

        def dfs(r, c):
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:
                return 0
            grid[r][c] = 0  # Mark the cell as visited
            area = 1
            area += dfs(r+1, c)
            area += dfs(r-1, c)
            area += dfs(r, c+1)
            area += dfs(r, c-1)
            return area

        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    max_area = max(max_area, dfs(r, c))

        return max_area

Time Complexity:

This solution efficiently computes the maximum area of an island using DFS without additional space for visited markers, by incorporating an in-place alteration of the grid itself.

Try our interview co-pilot at AlgoAdvance.com