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.
For this problem, let’s consider the following assumptions:
We’ll use Depth-First Search (DFS) to explore the grid. The main idea is:
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.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
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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?