使用dfs统计连通分量

如题所示,上代码:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
 
const int maxn = 10000;
char mp[maxn][maxn];
int m,n;
//方向数组,8个方向 
int dir[8][2]={{0,1},{1,0},{0,-1},{-1,0},{1,-1},{1,1},{-1,1},{-1,-1}};

void dfs(int x,int y){
	if(x<0||y<0||x>=m||y>=n) return;//越界处理 
	if(mp[x][y] != '@') return;//不是连通块里面的点或者是已经走过的点都不满足 
    	mp[x][y] = '&';//标记走过 
	for(int i = 0;i < 8;i++){
		int tx = x + dir[i][0];
		int ty = y + dir[i][1];
		if(mp[tx][ty]=='@') dfs(tx,ty); //继续走周围的点		    
	}
}

int main(){
	int cnt = 0;
	while(scanf("%d%d",&m,&n)==2&&m&&n){
	     cnt = 0;		
		for(int i = 0;i < m;i++) scanf("%s",mp[i]);
		for(int i = 0;i < m;i++)
		  for(int j = 0;j < n;j++)
		     if(mp[i][j]=='@'){
		     	cnt++;
		     	dfs(i,j);
			 }
	  cout<<cnt<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/JingleLiA/article/details/80615098
今日推荐