Description
请定一个无向图,顶点编号从0到n-1,用深度优先搜索(DFS),遍历并输出。遍历时,先遍历节点编号小的。
Input
输入第一行为整数n(0 < n < 100),表示数据的组数。 对于每组数据,第一行是两个整数k,m(0 < k < 100,0 < m < k*k),表示有m条边,k个顶点。 下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。
Output
输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示DFS的遍历结果。
Sample
Input
1
4 4
0 1
0 2
0 3
2 3
Output
0 1 2 3
#include<iostream>#include<bits/stdc++.h>usingnamespace std;bool Map[105][105],vis[105];int n,m;voidDFS(int x){
vis[x]=true;for(int i=0;i<n;i++){if(!vis[i]&& Map[x][i]){
cout<<" "<<i;DFS(i);}}}intmain(){
ios::sync_with_stdio(false);int t,u,v;
cin>>t;while(t--){memset(Map,false,sizeof(Map));memset(vis,false,sizeof(vis));
cin>>n>>m;for(int i=0;i<m;i++){
cin>>u>>v;
Map[u][v]= Map[v][u]=true;}
cout<<0;DFS(0);
cout<<endl;}return0;}