LeetCode695--岛屿的最大面积
1 ''' 2 岛屿的最大面积 3 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。 4 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。) 5 示例 1: 6 [[0,0,1,0,0,0,0,1,0,0,0,0,0], 7 [0,0,0,0,0,0,0,1,1,1,0,0,0], 8 [0,1,1,0,1,0,0,0,0,0,0,0,0], 9 [0,1,0,0,1,1,0,0,1,0,1,0,0], 10 [0,1,0,0,1,1,0,0,1,1,1,0,0], 11 [0,0,0,0,0,0,0,0,0,0,1,0,0], 12 [0,0,0,0,0,0,0,1,1,1,0,0,0], 13 [0,0,0,0,0,0,0,1,1,0,0,0,0]] 14 对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。 15 16 示例 2: 17 [[0,0,0,0,0,0,0,0]] 18 对于上面这个给定的矩阵, 返回 0。 19 注意: 给定的矩阵grid 的长度和宽度都不超过 50。 20 ''' 21 22 23 class Solution: 24 def maxAreaOfIsland(self, grid): 25 """ 26 :type grid: List[List[int]] 27 :rtype: int 28 """ 29 mx = 0 30 for i in range(len(grid)): 31 for j in range(len(grid[i])): 32 if grid[i][j] == 1: 33 num = self.deepSearch(grid, i, j) 34 mx = max(num, mx) 35 return mx 36 37 def deepSearch(self, g, i, j): 38 g[i][j] = 0 39 x = len(g) 40 y = len(g[0]) 41 c = 1 42 if i - 1 >= 0 and g[i - 1][j]: # 上 43 c = c + self.deepSearch(g, i - 1, j) 44 if j + 1 < y and g[i][j + 1]: # 右 45 c = c + self.deepSearch(g, i, j + 1) 46 if i + 1 < x and g[i + 1][j]: # 下 47 c = c + self.deepSearch(g, i + 1, j) 48 if j - 1 >= 0 and g[i][j - 1]: # 左 49 c = c + self.deepSearch(g, i, j - 1) 50 return c 51 52 53 if __name__ == '__main__': 54 grid = [[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], 55 [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], 56 [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 57 [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], 58 [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], 59 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 60 [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], 61 [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]] 62 ret = Solution().maxAreaOfIsland(grid) 63 print(ret)