题目
输入
6 8 1
1 2
2 3
3 4
4 5
5 6
6 4
3 6
1 5
输出
1 2 3 4 5 6 5 4 3 2 1
思路
为了保证输出从小到大,不妨使用set作为存放edge的容器
为了保证路可以回去,可以利用栈(递归)来进行道路的存放
DFS的过程中倘若未经过该点就存放该点在道路中,然后继续探索下一个连通的未经过的最小点,返回的时候如果确实经过该点了(返回1)就存放回来时候该点的数据
代码
#include<iostream>
#include<set>
#include<vector>
#include<cstring>
using namespace std;
set<int>edge[2000];
//由于要求从小到大,用set可以避免排序
int mark[2000];
vector<int> road;
int dfs(int x)
{
if(mark[x]) return 0;//来的时候已经走过这条路了
mark[x] = 1;
road.push_back(x);//回文的塞
for(auto data : edge[x])
{
if(dfs(data))
road.push_back(x);//走完前面的内容后,塞回去的路
}
return 1;//给回去的时候用 说明你经过了这个点
}
int main()
{
memset(mark, 0 ,sizeof(mark));
int N, M, start;
cin >> N >> M >> start;
for(int i = 0; i < M; i++)
{
int x;
int y;
cin >> x >> y;
edge[x].insert(y);
edge[y].insert(x);
}
dfs(start);
int flag = 0;
for(int i = 1; i <= N; i++)
if(!mark[i])
flag = 1;
for(auto x : road)
cout << x << " ";
if(flag)
cout << 0;
}