<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-27 10:21
已编辑
海南师范大学 媒介策划
到我怀里来:身高体重住址这些就别写了,留几个关键的就行,工作经历突出重点写详细点
点赞 评论 收藏
分享
2024-12-02 22:30
西安理工大学 Java
M_bao:简历排版换一下吧,第二个项目换了吧,咱门双非学历本来就不行还用这种项目太掉分了,300沟通一个要简历你打招呼也有问题。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务