<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                         

 

全部评论

相关推荐

2024-12-17 19:24
门头沟学院 Java
黑皮白袜臭脚体育生:看你后备隐藏能源多不多,最坏的情况就是每个星期的三天课程都不在周末,那么每个星期公司那边请一天半假,半天假请上午,上午正常上课,早点溜去请病假或者中午去请病假,然后坐高铁回公司,记得提前请学校那边实训课下午的病假,就说肚子痛,然后下午就公司上班,第二个实训周同样,但病假理由是牙齿痛,像肚子痛和牙齿痛这种校医院不方便查,会同意你出去检查的,很多时候都不需要你的检查报告,这里的问题就是最坏情况时距离过远的话可能要坐飞机才能赶上,然后请假的话不一定请了就有回应,可能要等老师,然后距离不远不近的情况到公司了也是迟到,得想个说辞掩盖一下,顺便晚上多加点班补下时间,特殊情况特殊处理,正常不建议加班常态化,这样每个星期可以多凑出来半天,老师面子也有了公司那边也不至于无法交差,就是有点费存粮,如果哪个星期的三天课有一天或两天在周末的话那就更好应对了。实习还是建议去,学校的课懂的都懂
点赞 评论 收藏
分享
联洲 嵌入式软件开发 总包48w(sp+3档)
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务