UVA-208 Firetruck (回溯)
题目大意:给一张无向图,节点编号从1到n(n<=20),按字典序输出所有从1到n的路径。
题目分析:先判断从1是否能到n,然后再回溯。
注意:这道题有坑,按样例输出会PE。
代码如下:
# include<iostream> # include<cstdio> # include<cstring> # include<algorithm> using namespace std; int mp[25][25],vis[25],ans; bool ok(int s,int e) { if(s==e) return true; vis[s]=1; for(int i=1;i<=20;++i) if(mp[s][i]&&!vis[i]&&ok(i,e)) return true; return false; } void dfs(int s,int e,string p) { if(s==e){ ++ans; int l=p.size(); for(int i=0;i<l;++i) printf("%d%c",p[i]-'A'+1,(i==l-1)?'\n':' '); } for(int i=1;i<=20;++i){ if(mp[s][i]&&!vis[i]){ vis[i]=1; dfs(i,e,p+char('A'+i-1)); vis[i]=0; } } } int main() { int n,a,b,cas=0; while(scanf("%d",&n)!=EOF) { memset(mp,0,sizeof(mp)); while(scanf("%d%d",&a,&b)&&a+b) mp[a][b]=mp[b][a]=1; printf("CASE %d:\n",++cas); ans=0; memset(vis,0,sizeof(vis)); if(ok(1,n)){ memset(vis,0,sizeof(vis)); vis[1]=1; dfs(1,n,"A"); } printf("There are %d routes from the firestation to streetcorner %d.\n",ans,n); } return 0; }