问题描述
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.)
思路
类似 200. Number of Islands
用dfs的思路
一个一个过,已经经过的点变成0
recur
class Solution:
def getIsland(self, grid, i, j, row, col, area):
if i < 0 or i >= row or j < 0 or j >= col or grid[i][j] ==0:
return area
grid[i][j] = 0
area += 1
area = self.getIsland(grid, i + 1, j, row, col, area)
area = self.getIsland(grid, i - 1, j, row, col, area)
area = self.getIsland(grid, i, j + 1, row, col, area)
area = self.getIsland(grid, i, j - 1, row, col, area)
return area
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or len(grid) == 0:
return 0
row = len(grid)
col = len(grid[0])
area = 0
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
tmp = self.getIsland (grid, i, j, row, col, 0)
area = max(tmp, area)
return area
网友评论