AC

lzhh_lzhh26  •  1个月前


#include<bits/stdc++.h>
using namespace std;
bool d[100][100];
bool vis[100];
int k,m,t;
void bfs(int t){
	queue<int> q;
	q.push(t);
	vis[t]=1;
	while(!q.empty()){
		int node=q.front();		
		vis[node]=1;		//标记:已走过 
		cout<<node<<' ';	//遍历到,输出 
		q.pop();		//弹出头 
		for(int i=0;i<k;i++){
			if(d[node][i]==1&&!vis[i]){		//没走过,连通 
				q.push(i);
				vis[i]=1; 
			}
		}
	}
}
int main(){
	int n;
	cin>>n;
	while(n--){
		cin>>k>>m>>t;		//k为点,m为边
		for(int i=0;i<m;i++){
			int f,e;
			cin>>f>>e;
			d[f][e]=1;
			d[e][f]=1;
		} 
		bfs(t);		//先从t开始遍历 
		for(int i=0;i<k;i++){
			if(!vis[i]) bfs(i);		//遍历其他块 
		}
		memset(d,0,sizeof d);
		memset(vis,0,sizeof vis);		//初始化 
	}
	return 0;
}

评论:

请先登录,才能进行评论