SHUOJ 1556三角迷宫(DFS)

题目:SHUOJ-1556

题目链接:http://202.121.199.212/JudgeOnline/problem.php?id=1556

题目:

1556: 三角迷宫

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 309   Solved: 226
[ Submit][ Status][ Web Board]

Description

这里有45个数字组成的一个三角阵,数字分别是1、2、3、...、9不等。要求你每次从顶点A处开始,一步步地通过它相邻的数字走到对边为止:但是一定要全部通过1,2,3,....,9这些数字,缺一不可,顺序不限,也不得重复,更不许走回头路。
                A 1
                  3 6
                9 7 8
              2 6 3 9
             3 1 5 8 5
           5 9 4 6 3 2
          8 3 2 9 4 9 1
         6 5 7 4 1 2 8 7
       7 1 4 8 7 4 5 6 2
对上述三角迷宫,我们可以找到一条路线,A 处:139654278。你能找出这一条路线来吗?

Input

输入有若干组测试数据,其第一行是整数n,表示三角迷宫的个数。接着有n 组测试数据,每一组是一个三角迷宫的描述,共9 行,第i 行上有i 个1 到9 之间的数字符号,i=1,2,„,9,每行上的数字符号之间有一个空格。两个三角迷宫之间有一个空行。

Output

对输入中描述的每组三角迷宫,确定从顶点A 出发,可否一步步地通过它相邻的数字走到对边为止,使路径上包含1,2,3„9 这全部9 个数字,顺序不限,不要重复,不许走回头路。先输出“Case#:”,其中“#”是三角迷宫的组号。如果从该顶点出发,可以确定这样的路线,则在下一行上输出“Possible”,否则输出“Impossible”。

Sample Input

2
1
3 6
9 7 8
2 6 3 9
3 1 5 8 5
5 9 4 6 3 2
8 3 2 9 4 9 1
6 5 7 4 1 2 8 7
7 1 4 8 7 4 5 6 2

4
3 6
9 7 8
2 6 3 9
3 1 5 8 5
5 9 4 6 3 2
8 3 2 9 4 9 1
6 5 7 4 1 2 8 7
7 1 4 8 7 4 5 6 2

Sample Output

Case 1:
Possible
Case 2:
Impossible
额,DFS,注意走的是相邻的路。。。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<math.h> 
using namespace std;
const int maxn=10;
int n,m;
int map[maxn][maxn];
int visit[maxn][maxn];
int vis[maxn];
bool ans=0;
int t;
void dfs(int x,int y){
	if(ans==1) return;
	if(x==9){
		ans=1;
		return;
	}
	
	for(int j=y;j<=y+1;j++){
		if(vis[map[x+1][j]]==0 && visit[x+1][j]==0){
			vis[map[x+1][j]]=x;
			visit[x+1][j]=1;
			dfs(x+1,j);
			visit[x+1][j]=0;
			vis[map[x+1][j]]=0;
		}
	}
}
int main(){
	int count=1;
	cin>>t;
	while(t--){
		for(int i=1;i<=9;i++){
			for(int j=1;j<=i;j++){
				visit[i][j]=0;
				cin>>map[i][j];
			}
			vis[i]=0;
		}
		ans=0;
		vis[map[1][1]]=1;
		dfs(1,1);
		cout<<"Case "<<count++<<":"<<endl;
		if(ans==1)
			cout<<"Possible"<<endl;
		else
			cout<<"Impossible"<<endl;
			
	}
	return 0;
}

Come on!


你可能感兴趣的:(DFS)