一道简单的路径打印,首先需要一次dfs判断能否从1到达目标点,否则可能会超时。还有一点就是那个格式需要注意下,每条路径前没有空格(看起来好像有3个空格)….
AC代码:
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=21+5;
int vis[maxn];
vector<int>G[maxn];
int cnt=0,goal;
void reach(int u){ //能否到达目标节点
vis[u]=1;
int len=G[u].size();
for(int i=0;i<len;++i){
if(G[u][i]==goal) {vis[goal]=1;return;}
if(!vis[G[u][i]]) reach(G[u][i]);
}
}
void dfs(int *a,int cur,int u){
if(u==goal){
cnt++;
//printf(" ");
for(int i=0;i<cur;++i){
if(i==0) printf("%d",a[i]);
else printf(" %d",a[i]);
}
printf("\n");
return;
}
int len=G[u].size();
for(int i=0;i<len;++i){
if(!vis[G[u][i]]){
vis[G[u][i]]=1;
a[cur]=G[u][i];
dfs(a,cur+1,G[u][i]);
vis[G[u][i]]=0;
}
}
}
void solve(){
memset(vis,0,sizeof(vis));
reach(1);
if(!vis[goal]) return; //从1无法到达目标节点
memset(vis,0,sizeof(vis));
for(int i=1;i<maxn;++i){
sort(G[i].begin(),G[i].end()); //排序的目的是方便按字典序输出
}
int a[maxn];
a[0]=1; //1作为起点
vis[1]=1;
dfs(a,1,1);
}
int main(){
int kase=0;
while(scanf("%d",&goal)==1){
cnt=0;
int x,y;
while(scanf("%d%d",&x,&y)==2&&x){
G[x].push_back(y);
G[y].push_back(x);
}
printf("CASE %d:\n",++kase);
solve();
printf("There are %d routes from the firestation to streetcorner %d.\n",cnt,goal);
for(int i=0;i<maxn;++i) G[i].clear();
}
return 0;
}
如有不当之处欢迎指出!