题目链接:http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=2074
典型的DFS题目,注意结束条件的判断。
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
bool map[15][15];
bool vis[15];
int res[15];
int n,m;//n表示有几个地点,m表示有几条路
bool DFS(int s,int d)//s表示当前开始的位置,d表示当前的深度
{
if(d==n-1) //结束条件的判断
{
if(map[s][1]==true)
return true;
return false;
}
for(int j=1;j<=n;j++)
{
if(j!=s && map[s][j]==true && !vis[j])
{
vis[j]=true;
bool t=DFS(j,d+1);
vis[j]=false; //注意恢复vis
if(t)
{
res[d]=j;
return true;
}
}
}
return false;
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
cin>>n>>m;
int m1,m2;
for(int i=0;i<m;i++)
{
cin>>m1>>m2;
map[m1][m2]=true;
map[m2][m1]=true;
}
vis[1]=true;
DFS(1,0);
cout<<1<<" ";
for(int j=0;j<n-1;j++)
{
cout<<res[j]<<" ";
}
cout<<1<<endl;
}
return 0;
}
仅代表个人观点,欢迎交流探讨,勿喷~~~
PhotoBy:WLOP