【广度优先遍历-中等】面试题 16.19. 水域大小

这篇博客探讨了两种解决二维数组中湖泊面积问题的方法。方法一是使用递归,通过深度优先搜索(DFS)遍历网格,方法二是利用栈来避免递归调用。这两种方法都用于计算零值(表示水)区域的大小,并最终返回排序后的湖泊面积列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

【代码】
【方法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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值