你有一张某海域NxN像素的照片,"."表示海洋、"#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
一个整数表示答案。
7 ....... .##.... .##.... ....##. ..####. ...###. .......
1
from queue import *
#广搜利用队列实现,不用递归
def bfs(x,y):
move =[(-1,0),(1,0),(0,-1),(0,1)]
flag = True
q= Queue()
q.put((x,y))
vis[x][y] =1
#检查连通块是否沉没
while not q.empty():
current=q.get()
x= current[0]
y =current[1]
#检查该点是否沉没
if a[x-1][y]=='#' and a[x+1][y]=='#'and a[x][y-1]=='#' and a[x][y+1]=='#':
flag = False
for i in range(4):
newx = x +move[i][0]
newy = y+ move[i][1]
if a[newx][newy]=='#' and vis[newx][newy] ==0:
q.put((newx,newy))
vis[newx][newy]=1
return flag
n =int(input())
#图像数组
a=[]
for i in range(n):
a.append(list(input()))
#状态数组
vis =[[0 for j in range(n)] for i in range(n)]
ans =0
#从左上角开始遍历图像
for i in range(n):
for j in range(n):
if a[i][j] =='#' and vis[i][j] ==0:
if bfs(i,j):
ans+=1
print(ans)