Problem description:

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

1
2
3
4
5
6
7
8
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:

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

Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.

Solution:

Regular DFS. We return the area for each dfs rotation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
# DFS to find the area of each island
# global variable to find max area across the grid
row, col, res = len(grid), len(grid[0]), 0
def dfs(i, j):
if 0 <= i < row and 0 <= j < col and grid[i][j]:
grid[i][j] = 0
return 1 + dfs(i+1, j) + dfs(i-1, j) + dfs(i, j+1) + dfs(i, j-1)
return 0

for i in range(row):
for j in range(col):
if grid[i][j] == 1:
res = max(res, dfs(i, j))
return res

BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
row, col, res = len(grid), len(grid[0]), 0
direction = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
# use queue to BFS
queue = collections.deque([])
queue.append((i, j))
grid[i][j] = 0
area = 1
while queue:
r, c = queue.popleft()
for d in direction:
dr, dc = r+ d[0], c + d[1]
if 0 <= dr < row and 0 <= dc < col and grid[dr][dc]:
area += 1
grid[dr][dc] = 0
queue.append((dr, dc))
res = max(res, area)
return res

time complexity: $O()$
space complexity: $O()$
reference:
related problem: