跳到正文

题解

at-abc325-C

xxr___约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年10月24日
收录
2026年10月13日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
9

版本

  1. v1当前

前言:

第一眼看到这个题,我想到油田那个题,大体思路就是有几个联通块,用深搜和广搜都可以。

附加知识:

联通块的个数就是从前往后枚举广搜则将这个点入队,将其能到达的符合要求的点入队,被更改过的即为同一个连通块。

广搜代码:

C++
#include<bits/stdc++.h>
using namespace std;
int n,m; 
char ch[1005][1005];
int dx[]={1,-1,0,0,-1,1,1,-1};
int dy[]={0,0,1,-1,1,1,-1,-1}; 
void bfs(int x,int y){
	queue<pair<int,int> > q;	
	q.push({x,y});
	while(q.size()){
		auto v=q.front();q.pop();
		for(int i=0;i<8;i++){
			int xx=v.first+dx[i],yy=v.second+dy[i];
			if(ch[xx][yy]=='#'&&xx>0&&xx<=n&&yy>0&&yy<=m){
				ch[xx][yy]='.';
				q.push({xx,yy});
			}
		}
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>ch[i][j];
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(ch[i][j]=='#'){
				ans++;
				bfs(i,j);
			}
		}
	}
	cout<<ans;
	return 0;
}

深搜代码:

C++
#include<bits/stdc++.h>
using namespace std;
int n,m; 
char ch[1005][1005];
int dx[]={1,-1,0,0,-1,1,1,-1};
int dy[]={0,0,1,-1,1,1,-1,-1}; 
void dfs(int x,int y){
	ch[x][y]='.';
	for(int i=0;i<8;i++){
		int xx=dx[i]+x;
		int yy=dy[i]+y;
		if(ch[xx][yy]=='#')dfs(xx,yy);
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>ch[i][j];
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(ch[i][j]=='#'){
				ans++;
				dfs(i,j);
			}
		}
	}
	cout<<ans;
	return 0;
}

感谢观看!