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

本文以Leetcode中695、岛屿的最大面积题目为基础进行展开(题目)。
求连通块的面积 - BFS、DFS实现_第1张图片


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实现)