【蓝桥杯】【BFS/DFS】全球变暖

题目描述

你有一张某海域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)
n =int(input())
map1=[]
cnt=0
#记录矩阵
martix =[[0 for j in range(n)]for i in range(n)]
#记录连通块情况
ans =[0 for i in range(n)]
move =[(-1,0),(1,0),(0,-1),(0,1)]
#连通块个数
len1=0
for i in range(n):
    map1.append(input())
def dfs(pos,k):
    if map1[pos[0]][pos[1]] !='#':
        return 
    if map1[pos[0]-1][pos[1]] !='.' and map1[pos[0]+1][pos[1]] !='.' and map1[pos[0]][pos[1]-1] !='.' and map1[pos[0]][pos[1]+1] !='.':
        ans[k]+=1 
    martix[pos[0]][pos[1]] =1 
    for i in move:
        new_x = pos[0] +i[0]
        new_y = pos[1] +i[1]
        if martix[new_x][new_y] ==0:
            dfs((new_x,new_y),k)
        
                
                
for i in range(1,n):
    for j in range(n):
        if map1[i][j] =='#' and martix[i][j]==0:
            dfs((i,j),len1)
            len1+=1
for i in range(len1):
    if ans[i]==0:
        cnt+=1 
print(cnt)

            

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值