python bfs模板题

找出n行m列的二维数组中的岛屿数量(岛屿表示所有相邻1的集合,上下左右才相邻)
输入:

12 14
10111000011100
01100110001101
00000111000011
00110000001000
00011000111000
00111100010011
10011101100111
11000100000001
00000000011000
00000000000000
10001100110000
10001000011111

输出:

14
from collections import deque
row, col = (int(x) for x in input().split())
g, st = [], [] # g记录地图,st标记是否走过
cnt = 0
ne = [[-1, 0], [0, -1], [1, 0], [0, 1]]
for i in range(row):
    g.append(input())
    st.append([0]*col)
for i in range(row):
    for j in range(col):
        if st[i][j] == 0 and g[i][j] == '1':
            cnt += 1 #岛屿数+1
            #以下为bfs标记所有相邻的1
            que = deque([[i, j]]) # 双端队列模拟队列
            while que:
                x, y = que.popleft()
                st[x][y] = 1
                for k in range(4):
                    tx = ne[k][0] + x
                    ty = ne[k][1] + y
                    if tx < 0 or tx >= row or ty < 0 or ty >= col:
                        continue
                    if g[tx][ty] == '1' and st[tx][ty] == 0:
                        que.append([tx, ty])

print(cnt)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值