695岛屿的最大面积

题目:给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)

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

法一:自己的代码

思路:同200岛屿数量一样,一旦遇到一个1,则深度优先遍历,将该岛屿的面积算出来保存,最后返回最大值,注意用另一个数组记录是否遍历过了,还有个技巧是一旦遍历过某个位置是1了,就将其置为0,也就是在原数组上修改,可以节省空间。

from typing import List
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        r_length = len(grid)
        c_length = len(grid[0])
        directions = [[0,1],[0,-1],[1,0],[-1,0]]
        marked = [[False] * c_length for i in range(r_length)]
        result = []

        for r in range(r_length):
            for c in range(c_length):
                # 如果没有被遍历过,且为1则进行遍历
                if not marked[r][c] and grid[r][c] == 1:
                    cou = 1
                    # 先将该位置置为True,表示已经遍历过了
                    marked[r][c] = True
                    # 将与该位置相连的所有的1,都置为True,表示已经遍历过,
                    queue = []
                    queue.append((r, c))
                    while queue:
                        r, c = queue.pop(0)
                        for p, q in directions:
                            # 注意这里的新位置要用新的变量存储,不可用原先的r,c
                            r_new = r + p
                            c_new = c + q
                            if 0 <= r_new < r_length and 0 <= c_new < c_length and grid[r_new][c_new] == 1 and not marked[r_new][c_new]:
                                # 放入队列,等待遍历
                                queue.append((r_new, c_new))
                                # 遍历过的位置,且为'O'的都置为True,
                                marked[r_new][c_new] = True
                                cou += 1
                    result.append(cou)
        return max(result)
if __name__ == '__main__':
    solution = Solution()
    result = solution.maxAreaOfIsland()
    print(result)
View Code

ttt

猜你喜欢

转载自www.cnblogs.com/xxswkl/p/12292722.html
今日推荐