找出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)