图的连通块(DFS)

图的连通块

思路:dfs,把每个点与之相连的点都存入vector,然后每个点搜过去,并且标记,防止重复搜,每循环搜完一次就计数,最后输出即可。
注意点

dfs里的循环变量要定义成局部变量,不然会和上一层的dfs产生冲突。

代码

#include<bits/stdc++.h>
using namespace std;
vector<int>a[10001];
bool b[10001];
int n,m,x,y,t,i;
void dfs(int node){
    
    
	b[node]=true;
	int l=a[node].size();
	for(int i=0;i<l;i++)
		if(!b[a[node][i]])
			dfs(a[node][i]);
}
int main(){
    
    
	cin>>n>>m;
	while(m--){
    
    
		cin>>x>>y;
		a[x].push_back(y);
		a[y].push_back(x);
	}
	for(i=1;i<=n;i++)
		if(!b[i]){
    
    
			t++;
			dfs(i);
		}
	cout<<t;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_52536621/article/details/113794124
今日推荐