AC

lzhh_lzhh26  •  1个月前


#include<bits/stdc++.h>
using namespace std;
bool d[110][110];	//有向图
bool vis[110]; 
int n,m;
void dfs(int node){
	vis[node]=1;
	cout<<node<<' ';
	for(int i=1;i<=n;i++){
		if(vis[i]==0&&d[node][i]==1){
			dfs(i); 
		}
	}
}
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=1;i<=n;i++){
			if(d[node][i]==1&&!vis[i]){		//没走过,连通 
				q.push(i);
				vis[i]=1; 
			}
		}
	}
}
int main(){
	cin>>n>>m;		//n节点m边 
	for(int i=0;i<m;i++){		//编号1到n 
		int from,to;
		cin>>from>>to;
		d[from][to]=1;
	}
	dfs(1);
	cout<<endl;
	memset(vis,0,sizeof vis);
	bfs(1);
	
	
	return 0;
} 

/*
Q:
8 9
1 2
1 3
1 4
2 5
2 6
3 7
4 7
4 8
7 8

A:
1 2 5 6 3 7 8 4 
1 2 3 4 5 6 7 8 

*/

评论:

请先登录,才能进行评论