<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                         

 

全部评论

相关推荐

06-27 18:53
门头沟学院 Java
这样才知道自己不适合搞代码,考公去咯
只爱喝白开水:我也发现不适合搞代码,打算转非技术方向了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-04 15:20
牛客61197583...:看到室友一个个没怎么学通过关系直接入职或者接到面试,真的很难受。八股不知道背了多少遍,hot100也刷了1.5遍了,但就是没有面试的机会,唉
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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