http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=8
注意dfs函数里for循环中的i前一定要加int,代表此处的i为局部变量(ps:开始没加int错了好长时间没看出来哪里错了),不这样的话,
向前回溯时,每次i的值都被后面的i更新了,影响了原本i的值;
---------------------------------------------------------------------------------------------------------------------------------
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
using namespace std;
int n,diff,map[50][4],numcard[50];//边长,牌的种类数,每种牌的序列,每种牌的数量
int i,j,game=1,shunxu[50];//shunxu数组为卡牌排放的顺序
int up,down,_right,left;
bool dfs(int pos)
{
if(pos==n*n) return true;
for(int i=0;i!=diff;i++)
{
if(numcard[i]==0) continue;//如果数目不够或不符合要求,更换新种类的卡牌
if(pos%n!=0&&map[i][3]!=map[shunxu[pos-1]][1]) continue;
if(pos/n!=0&&map[shunxu[pos-n]][2]!=map[i][0]) continue;
shunxu[pos]=i;
--numcard[i];
if(dfs(pos+1)) return true;//向下递归
else ++numcard[i];
}
return false;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(map,0,sizeof(map));
memset(numcard,0,sizeof(numcard));
memset(shunxu,0,sizeof(shunxu));
diff=0;
if(n==0) break;
for(i=0;i!=n*n;i++)//存图
{
scanf("%d%d%d%d",&up,&_right,&down,&left);
for(j=0;j<diff;j++)//用于判重
{
if(up==map[j][0]&&_right==map[j][1]&&down==map[j][2]&&left==map[j][3])
{
break;
}
}
if(diff==j)//如果有新的卡牌,
{
numcard[j]=1;
++diff;//增加卡牌的数量
map[j][0]=up;map[j][1]=_right;map[j][2]=down;map[j][3]=left;
}
else ++numcard[j];
}
if(game!=1) printf("\n");
if(dfs(0)) printf("Game %d: Possible\n",game);
else printf("Game %d: Impossible\n",game);
game++;
}
return 0;
}