lettcode面试题目16.19

题目链接

class Solution:
    def pondSizes(self, land: List[List[int]]) -> List[int]:
        if len(land)==0:return []
        directions=[(-1,0),(1,0),(0,-1),(0,1),(-1,1),(-1,-1),(1,-1),(1,1)]
        res,m,n=[],len(land),len(land[0])
        for i in range(m):
            for j in range(n):
                if land[i][j]==0:
                    queue=[(i,j)]
                    land[i][j]=1
                    cnt=1
                    while queue:
                        next_queue=[]
                        for old_x,old_y in queue:
                            for direction in directions:
                                new_x,new_y=old_x+direction[0],old_y+direction[1]
                                if 0<=new_x<m and 0<=new_y<n and land[new_x][new_y]==0:
                                    land[new_x][new_y]=1
                                    cnt+=1
                                    next_queue.append((new_x,new_y))
                        queue=next_queue
                    res.append(cnt)
        res.sort()
        return res              

BFS计算有多少个8方向连接的岛屿,并且按照岛屿的面积从小到大输出一个列表。

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务