首页 > 其他 > 详细

求连通块的面积 - BFS、DFS实现

时间:2019-12-11 16:22:43      阅读:177      评论:0      收藏:0      [点我收藏+]

本文以Leetcode中695、岛屿的最大面积题目为基础进行展开(题目??)。
技术分享图片


DFS实现
class Solution:
    def maxAreaOfIsland(self, grid) -> int:
        directx = [-1, 1, 0, 0]
        directy = [0, 0, -1, 1]
        vis = set()
        res = 0
        def DFS(x, y, area):
            for t in range(4):
                newx, newy = x + directx[t], y + directy[t]
                if  -1 < newx < len(grid) and -1 < newy < len(grid[0]) and grid[newx][newy] == 1 and (newx, newy) not in vis:
                    vis.add((newx, newy))
                    area += DFS(newx, newy, 1)
            return area
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1 and (i, j) not in vis:
                    vis.add((i, j))
                    res = max(DFS(i, j, 1), res)
        return res

BFS实现
class Solution:
    def maxAreaOfIsland(self, grid) -> int:
        directx = [-1, 1, 0, 0]
        directy = [0, 0, -1, 1]
        vis = set()
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1 and (i, j) not in vis:
                    vis.add((i, j))
                    stack = [(i, j)]
                    ans = 1
                    while len(stack) != 0:
                        x, y = stack.pop(0)
                        for t in range(4):
                            newx, newy = x + directx[t], y + directy[t]
                            # 判断是否为可以走得通的路径
                            if -1 < newx < len(grid) and -1 < newy < len(grid[0]) and (newx, newy) not in vis and grid[newx][newy] == 1:
                                vis.add((newx, newy))
                                ans += 1
                                stack.append((newx, newy))
                    res = max(res, ans)
        return res

求连通块的面积 - BFS、DFS实现

原文:https://www.cnblogs.com/NFii/p/12022458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!