【Leetcode 深搜、广搜】岛屿的最大面积(695)

题目

给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。

找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)

示例 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]

对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。

示例 2:

[[0,0,0,0,0,0,0,0]]

对于上面这个给定的矩阵, 返回 0。

注意: 给定的矩阵grid 的长度和宽度都不超过 50。

解答

典型的搜索题,深度优先和广度优先都可以。(比较简单,不记录思路了)

1,深度优先dfs,用递归。Time: O(mn),Space:O(mn)
2,广度优先bfs,用队列。Time: O(mn),Space:O(mn)

# 深搜

class Solution:
    def __init__(self):
        self.a = []
        self.book = []
        self.next = [
            [0, 1],
            [1, 0],
            [0, -1],
            [-1, 0]
        ]
        self.m = 0
        self.n = 0
        self.max = 0

    def maxAreaOfIsland(self, grid) -> int:
        if not grid:
            return 0
        self.a, self.m, self.n = grid, len(grid), len(grid[0])
        self.book = [
            [0 for _ in range(self.n)] for _ in range(self.m)
        ]
        max = 0
        for i in range(self.m):
            for j in range(self.n):
                if self.a[i][j] == 1:
                    self.max = 0
                    self.book[i][j] = 1
                    self.max += 1
                    self.dfs(i, j)
                    if self.max > max:
                        max = self.max
        return max

    def dfs(self, x, y):
        for i in range(4):
            tx = x + self.next[i][0]
            ty = y + self.next[i][1]
            if tx >= 0 and ty >= 0 and tx < self.m and ty < self.n and self.book[tx][ty] == 0 and self.a[tx][ty] == 1:
                self.max += 1
                self.book[tx][ty] = 1
                self.dfs(tx, ty)
                # 不取消标记,只走一次即可


s = Solution()
ans = s.maxAreaOfIsland([[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                         [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
                         [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                         [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
                         [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
                         [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                         [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
                         [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]])
print(ans)
# 6
上一篇:二分图——棋盘覆盖


下一篇:深度优先搜索 模板+例题