描述
The following is a triangle array with 45 numbers from 1, 2, 3, …, 9.
In the above array we find the road 139654278 from A to the bottom. Now your job is find such a
road from A to the bottom.
输入
The input contains several cases. On the first line is a integer n, which is the triangle arrays. Then
follows the descriptions of the n cases. the data of each case consists of 9 lines. On the i-th line contains i symbols from 1 to 9. There is a blank line between two descriptions.
输出
For each triangle, determine if you can find the road from A to the bottom. The road must contain
the 9 symbols from 1 to 9, and they are different. You are not allowed to return to the above line. First
you print “Case #:”, where # is the number of the case. If you can not find such road you print
“Impossible”, otherwise print “Possible”.
样例输入
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
样例输出
Case 2:Impossible
#include<iostream>
#include<stdio.h>
using namespace std;
int cp[9][9], sam[9]={1,3,9,6,5,4,2,7,8};
bool flag;
void dfs(int x,int y,int k)
{
if(x==9)
{
flag=true;
return ;
}
if(cp[x][y]==sam[k])
{
if(cp[x+1][y]==sam[k+1]) dfs(x+1,y,k+1);
if(cp[x+1][y+1]==sam[k+1] && !flag) dfs(x+1,y+1,k+1);
}
}
int main()
{
int ca, i, j, k;
scanf("%d",&ca);
k=1;
while(k<=ca)
{
for(i=0;i<9;i++)
for(j=0;j<=i;j++)
cin>>cp[i][j];
flag=false;
dfs(0,0,0);
cout<<"Case "<<k<<":";
if(flag) cout<<"Possible"<<endl;
else cout<<"Impossible"<<endl;
k++;
}
return 0;
}