码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode刷题】岛屿的最大面积

时间:2020-03-15 22:09:02      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:list   tps   sla   遇到   广度   -o   grid   计算   max   

题目: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

【Leetcode刷题】岛屿的最大面积

标签:list   tps   sla   遇到   广度   -o   grid   计算   max   

原文地址:https://www.cnblogs.com/luozx207/p/12500320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!