695. Max Area of Island

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

solution

典型二维DFS

  • 递归

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        if not grid:
            return 0

        m = len(grid)
        n = len(grid[0])

        dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        visited = [[False] * n for _ in range(m)]
        res = 0

        for i in range(m):
            for j in range(n):
                if not visited[i][j] and grid[i][j] == 1:
                    self.count = 0  # 注意这里如果不用self, 直接递归里传值会一直是0. 因为是Immutable
                    # 或者结果在递归间的传递: https://algo.monster/liteproblems/695
                    self.dfs(grid, i, j, dirs, visited, m, n)
                    res = max(res, self.count)
        return res

    def dfs(self, grid, i, j, dirs, visited, m, n):
        if visited[i][j] or grid[i][j] == 0:
            return

        visited[i][j] = True
        self.count += 1

        for dir in dirs:
            ni = i + dir[0]
            nj = j + dir[1]
            if 0 <= ni < m and 0 <= nj < n:
                self.dfs(grid, ni, nj, dirs, visited, m, n)

时间复杂度:O() 空间复杂度:O()

  • 非递归

时间复杂度:O() 空间复杂度:O()

Last updated