原题
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:
[[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:
[[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.
解法
DFS. 先遍历grid, 当遇到1时, 求当前小岛的面积, 定义dfs函数返回小岛的面积, base case是当i, j超出了索引范围或者grid[i][j] 为0时, 返回0. 然后将走过的小岛标记为0, 返回 1+相邻小岛的面积.
Time: O(m*n)
Space: O(1)
代码
class Solution:
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def dfs(i, j):
if 0 <= i < row and 0<= j < col and grid[i][j] == 1:
grid[i][j] = 0
return 1 + dfs(i-1, j) + dfs(i+1, j) + dfs(i, j-1) + dfs(i, j+1)
return 0
row, col = len(grid), len(grid[0])
ans = 0
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
ans = max(ans, dfs(i, j))
return ans