岛屿最大面积
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例 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]]
对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。
示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。
注意: 给定的矩阵grid 的长度和宽度都不超过 50。
class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ if len(grid)==0: return 0 mas = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]==0: continue num = 0 land = [(i,j)] while land: r,n =land.pop() if grid[r][n]==0: continue grid[r][n]=0 num+=1 if r》0 and grid[r-1][n]==1: land.append((r-1,n)) if r《len(grid)-1 and grid[r+1][n]==1: land.append((r+1,n)) if n》0 and grid[r][n-1]==1: land.append((r,n-1)) if n《len(grid[0])-1 and grid[r][n+1]==1: land.append((r,n+1)) mas = max(mas,num) return mas