[Title] Leetcode brush the largest area of the island

Topic: https://leetcode-cn.com/problems/max-area-of-island/

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        # 遇到1后,对小岛进行广度优先搜索计算面积,并将遍历过的小岛沉没,避免再次计算
        height = len(grid)
        length = len(grid[0])

        def get_area(x, y):
            # 广度优先搜索求面积
            area = 1
            queue = [(x, y)]
            grid[x][y] = 0
            while queue:
                i, j = queue.pop(0)
                # 上
                if i-1 >= 0 and grid[i-1][j] == 1:
                    area += 1
                    queue.append((i-1, j))
                    grid[i - 1][j] = 0
                # 下
                if i+1 < height and grid[i+1][j] == 1:
                    area += 1
                    queue.append((i+1, j))
                    grid[i + 1][j] = 0
                # 左
                if j-1 >= 0 and grid[i][j-1] == 1:
                    area += 1
                    queue.append((i, j-1))
                    grid[i][j - 1] = 0
                # 右
                if j+1 < length and grid[i][j+1] == 1:
                    area += 1
                    queue.append((i, j+1))
                    grid[i][j + 1] = 0
            return area

        max_area = 0
        for i in range(height):
            for j in range(length):
                if grid[i][j] == 1:
                    area = get_area(i, j)
                    if area > max_area:
                        max_area = area
        return max_area

Guess you like

Origin www.cnblogs.com/luozx207/p/12500320.html