[蓝桥杯][2018年第九届真题]全球变暖

题目链接:全球变暖



解题思路:当遇到陆地时就宽搜这块陆地,每一块陆地判断周边是否有海,如果有海证明会被淹没,最后判断淹没的数量和这块陆地的大小是否相同,如果相同,那么证明这整块陆地已经被淹没

#include<bits/stdc++.h>
#define x first
#define y second
#define mem1(h) memset(h,-1,sizeof h)
#define mem0(h) memset(h,0,sizeof h)
#define mcp(a,b) memcpy(a,b,sizeof b)
using namespace std;
typedef long long LL;
typedef unsigned long long ull; 
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
namespace IO{
    
    
	inline LL read(){
    
    
		LL o=0,f=1;char c=getchar();
		while(c<'0'||c>'9'){
    
    if(c=='-')f=-1;c=getchar();}
		while(c>='0'&&c<='9'){
    
    o=o*10+c-'0';c=getchar();}
		return o*f;
	}
}using namespace IO;
//#############以上是自定义技巧(可忽略)########## 
const int N=1e3+7,M=2e5+7,INF=0x3f3f3f3f,mod=1e8+7,P=131;
int n,ans;
char g[N][N];
bool st[N][N];
int dx[4]={
    
    1,0,-1,0},dy[4]={
    
    0,1,0,-1};
void bfs(int x,int y,int &cnt,int &flood){
    
    
	queue<PII>q;
	st[x][y]=true;
	q.push({
    
    x,y});
	while(!q.empty()){
    
    
		PII u=q.front();q.pop();
		if(g[u.x][u.y]=='#')cnt++;//如果是陆地,数量就+1
		int flag=0;//用于判断是否被淹没过
		for(int i=0;i<4;i++){
    
    
			int tx=u.x+dx[i],ty=u.y+dy[i];
			if(tx<0||tx>=n||ty<0||ty>=n)continue;
			if(st[tx][ty])continue;
			if(g[tx][ty]=='.'){
    
    //如果周边有海
				if(!flag){
    
    //如果没有被淹没过那么第一次被淹没
					flag=1;
					flood++;
				}
				continue;//否则曾经被淹没过则跳过
			}
			st[tx][ty]=1;
			q.push({
    
    tx,ty});
		}
	}	
}
int main(){
    
    
    cin>>n;
	for(int i=0;i<n;i++){
    
    
		cin>>g[i];
	}
	for(int i=0;i<n;i++){
    
    
		for(int j=0;j<n;j++){
    
    
			if(g[i][j]=='#'&&st[i][j]==0){
    
    
				int cnt=0,flood=0;//cnt表示这整块陆地de大小,flood表示这块陆地被淹没的数量
				bfs(i,j,cnt,flood);//从这块陆地开始搜索整块相连的陆地
				ans+=(cnt==flood);//如果陆地大小和淹没数量一样,那么这整块陆地被淹没
			}
		}
	}
	cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43738764/article/details/109055103