leetcode 200. Number of Islands

博客围绕计算二维网格中岛屿数量的问题展开,介绍用Python重新实现BFS算法来解决该问题。指出在写BFS时可新建列表,用元组表示位置下标添加到列表。还提醒不能用grid[r, c] == '0'这种适用于NumPy数组的写法,具体思路可查看博客园链接。

摘要生成于 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.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

具体的思路可以见我的博客园的博客:https://www.cnblogs.com/Weixu-Liu/p/10712642.html

在这个题中,我用python重新写BFS,在写BFS中,可以新建立一个列表,把位置下标用元组表示,加到列表中就行。

python代码:
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        sum = 0
        q = []
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        dx = [0,0,1,-1]
        dy = [1,-1,0,0]
        for r in range(m):
            for c in range(n):
                if grid[r][c] == '1':
                    grid[r][c] == '0'
                    q.append((r,c))
                    while len(q):
                        Q = q.pop(0)
                        index_r = Q[0]
                        index_c = Q[1]
                        for i in range(4):
                            x = index_r + dx[i]
                            y = index_c + dy[i]
                            if x >= 0 and x < m and y >= 0 and y < n and grid[x][y] == '1':
                                grid[x][y] = '0'
                                q.append((x,y))
                    sum += 1
        return sum
PS

不能写grid[r, c] == '0',这个是在NumPy中的array数组上能用的。。。在列表就行不通了,o(╯□╰)o

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值