Leetcode题200、岛屿数量(Python题解)

该博客介绍了LeetCode第200题‘岛屿数量’的Python解决方案,通过DFS和BFS两种方法,分析了算法思路,并讨论了它们的时间复杂度为O(mn)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题
在这里插入图片描述

题目来源:力扣(LeetCode)

leetcode200.岛屿数量

难度:中等

分析
DFS和BFS都可以做,对每一块陆地进行搜索,搜索过的陆地就标记成海洋,不再搜索,则搜索陆地的次数就是陆地的数量。

解决方法
1:DFS

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid: return 0   #边界条件,如果矩阵是空的,那么肯定没有岛
        
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '1':
                    self.dfs(grid, i, j)
                    count += 1
        return count
    def dfs(self, grid, i, j):
        if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] != '1':
            return 
        grid[i][j] = '0'
        for m, n in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
            self.dfs(grid, m, n)

复杂度:O(mn)

2:BFS

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        count = 0
        for row in range(len(grid)):
            for col in range(len(grid[0])):
                if grid[row][col] == '1':  # 发现陆地
                    count += 1  # 结果加1
                    grid[row][col] = '0'  # 将其转为 ‘0’ 代表已经访问过
                    # 对发现的陆地进行扩张即执行 BFS,将与其相邻的陆地都标记为已访问
                    # 下面还是经典的 BFS 模板
                    land_positions = collections.deque()
                    land_positions.append([row, col])
                    while len(land_positions) > 0:
                        x, y = land_positions.popleft()
                        for new_x, new_y in [[x, y + 1], [x, y - 1], [x + 1, y], [x - 1, y]]:  # 进行四个方向的扩张
                            # 判断有效性
                            if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]) and grid[new_x][new_y] == '1':
                                grid[new_x][new_y] = '0'  # 因为可由 BFS 访问到,代表同属一块岛,将其置 ‘0’ 代表已访问过
                                land_positions.append([new_x, new_y])
        return count

复杂度:O(mn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值