码迷,mamicode.com
首页 > 其他好文 > 详细

Strange Country II ( 简单的dfs,但是要注意细节)

时间:2015-05-04 22:13:34      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:dfs   bfs   遍历   地图   

Strange Country II

You want to visit a strange country. There are n cities in the country. Cities are numbered from 1 to n. The unique way to travel in the country is taking planes. Strangely, in this strange country, for every two cities A and B, there is a flight from A to B or from B to A, but not both. You can start at any city and you can finish your visit in any city you want. You want to visit each city exactly once. Is it possible?

Input

There are multiple test cases. The first line of input is an integer T (0 < T <= 100) indicating the number of test cases. Then T test cases follow. Each test case starts with a line containing an integer n (0 < n <= 100), which is the number of cities. Each of the next n * (n - 1) / 2 lines contains 2 numbers AB (0 < AB <= nA != B), meaning that there is a flight from city A to city B.

Output

For each test case:

  • If you can visit each city exactly once, output the possible visiting order in a single line please. Separate the city numbers by spaces. If there are more than one orders, you can output any one.
  • Otherwise, output "Impossible" (without quotes) in a single line.

Sample Input

3
1
2
1 2
3
1 2
1 3
2 3

Sample Output

1
1 2
1 2 3
题意大概是:
给你n个城市,然后告诉你哪两个城市有连边,然后叫你判断能否一次性就走完地图上所有的点,若可以,则输出遍历的过程,否则,输出impossible!
直接对每一个点进行一遍dfs,然后判断一下就好了。
只是要注意细节!
在dfs中,只有在ff为真的时候才不用清零值,否则,return了之后要像我代码中所写的那样,tot--之类的。
#include<stdio.h>
#include<string.h>
#define maxn 111
#define INF 99999999
int e[maxn][maxn],k=0;
int book[maxn]={0},que[maxn];
bool ff=false;
int tot=0;
void dfs(int cur,int n){
	que[tot++]=cur;
	if(tot==n){
		ff=true;
		return ;
	}
	for(int i=1;i<=n;i++){
		if(e[cur][i]!=INF&&book[i]==0){
			book[i]=1;
			dfs(i,n);	
			//这里是细节,只有找到了才是返回;		
			if(ff) return ;
			//否则的话,那么就要进行复原操作; 
			book[i]=0;
			//注意tot--; 
			tot--;
		}
	}
}
int main(){
	int T,i,j;
	int n,a,b;
	while(~scanf("%d",&T)){
		while(T--){
			memset(e,0,sizeof(e)); memset(book,0,sizeof(book));
			memset(que,0,sizeof(que));
			scanf("%d",&n);
			for(i=1;i<=n;i++)
				for(j=1;j<=n;j++)
				e[i][j]=INF;
			int tt=n*(n-1)/2;
			while(tt--){
				scanf("%d%d",&a,&b);
				e[a][b]=1;
			}
			k=0;
			ff=false;
			tot=0;
			//其实质就是对每个点进行搜一遍,然后找是否有可行解; 
			for(i=1;i<=n;i++){
				//注意每次都要进行清零操作; 
				memset(que,0,sizeof(que));
				memset(book,0,sizeof(book));
				tot=0;
				if(book[i]==0){
					book[i]=1;
					dfs(i,n);
					if(ff) break;
				}
			}
			if(!ff) printf("Impossible\n");
			else{
				for(int l=0;l<tot;l++){
					if(l!=tot-1) printf("%d ",que[l]);
					else printf("%d\n",que[l]);
				}
			}
		}
	}
}


Strange Country II ( 简单的dfs,但是要注意细节)

标签:dfs   bfs   遍历   地图   

原文地址:http://blog.csdn.net/acmer_hades/article/details/45485413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!