<span>leetcode -695 Max Area of Island</span>

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.)

input:
[[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]]
output:
6

这道题就是一个简单的搜索问题,代码比较简单。

 1 class Solution:
 2     def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
 3         maxIsland = 0
 4         for i in range(len(grid)):
 5             for j in range(len(grid[0])):
 6                 if grid[i][j] == 1:
 7                     grid[i][j] = 0
 8                     stack = []
 9                     count = 0
10                     stack.append((i, j))
11                     while len(stack) != 0:
12                         (x, y) = stack.pop()
13                         count += 1
14                         if x - 1 >= 0 and grid[x - 1][y] == 1:
15                             stack.append((x - 1, y))
16                             grid[x - 1][y] = 0
17                         if x + 1 < len(grid) and grid[x + 1][y] == 1:
18                             stack.append((x + 1, y))
19                             grid[x + 1][y] = 0
20                         if y - 1 >= 0 and grid[x][y - 1] == 1:
21                             stack.append((x, y - 1))
22                             grid[x][y - 1] = 0
23                         if y + 1 < len(grid[0]) and grid[x][y + 1] == 1:
24                             stack.append((x, y + 1))
25                             grid[x][y + 1] = 0
26                     if count > maxIsland:
27                         maxIsland = count
28         return maxIsland
29                         

 

全部评论

相关推荐

没有奇迹的世界:简直世另我 一样的先学后端再转前端一样的简历模板 绷不住了甚至描述都这么像 值得庆幸的是你才28届 加油
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务