【题目】
【代码】
【方法1】递归方法求解

class Solution:
def pondSizes(self, land: List[List[int]]) -> List[int]:
ans=[]
def dfs(x,y):
if x>=0 and x<len(land) and y>=0 and y<len(land[0]) and land[x][y]==0:
land[x][y]=1
return 1+dfs(x+1,y)+dfs(x-1,y)+dfs(x,y+1)+dfs(x,y-1)+dfs(x-1,y-1)+dfs(x+1,y+1)+dfs(x-1,y+1)+dfs(x+1,y-1)
return 0
for i in range(len(land)):
for j in range(len(land[0])):
if land[i][j]==0:
tmp=dfs(i,j)
if tmp:
ans.append(tmp)
ans.sort()
return ans
【方法2】用栈代替递归

class Solution:
def pondSizes(self, land: List[List[int]]) -> List[int]:
ans=[]
for i in range(len(land)):
for j in range(len(land[0])):
if land[i][j]==0:
cnt=0
stack=[(i,j)]
while stack:
x,y=stack.pop()
if x>=0 and x<len(land) and y>=0 and y<len(land[0]) and land[x][y]==0:
land[x][y]=1
cnt+=1
stack.append((x+1,y))
stack.append((x-1,y))
stack.append((x,y+1))
stack.append((x,y-1))
stack.append((x-1,y-1))
stack.append((x+1,y+1))
stack.append((x-1,y+1))
stack.append((x+1,y-1))
if cnt:
ans.append(cnt)
ans.sort()
return ans
这篇博客探讨了两种解决二维数组中湖泊面积问题的方法。方法一是使用递归,通过深度优先搜索(DFS)遍历网格,方法二是利用栈来避免递归调用。这两种方法都用于计算零值(表示水)区域的大小,并最终返回排序后的湖泊面积列表。
4万+

被折叠的 条评论
为什么被折叠?



