LeetCode 200. Number of Islands [Python]

本文介绍了一种使用宽度优先搜索算法来计算二维网格中岛屿数量的方法。岛屿由'1'(陆地)组成,被'0'(水域)包围,通过水平或垂直连接形成。文章详细解释了如何遍历整个图,标记访问过的节点,并统计岛屿数量。

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

Given a 2d grid map of '1’s (land) and '0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

  1. 宽度优先搜索四个方向遍历整个图
  2. 访问过的节点标记为0
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        count = 0
        if not grid or not grid[0]:
            return count
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '1':
                    self.bfs(grid, i, j)
                    count += 1
        return count
    
    def bfs(self, grid, i, j):
        queue = collections.deque([(i,j)])
        grid[i][j] = '0'
        while queue:
            x, y = queue.popleft()
            for delta_x, delta_y in [(1,0), (0,1), (-1,0), (0,-1)]:
                new_x, new_y = x + delta_x, y + delta_y
                if not self.valid(grid, new_x, new_y):
                    continue
                queue.append((new_x, new_y))
                grid[new_x][new_y] = '0'
    
    def valid(self, grid, i, j):
        m, n = len(grid), len(grid[0])
        return 0 <= i < m and 0 <= j < n and grid[i][j] == '1'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值