题目来源:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=8
之前的写法:http://blog.csdn.net/hearthougan/article/details/12357801
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 25;
int Graph[MAXN][4];//最多总共有25种类型
int kcount[MAXN];//存放每种类型的个数
int iTable[MAXN];//存放放置的方案
int n, ikinds;//ikinds表示方块的种类数
bool DFS(int iPos)
{
if(iPos == n*n)
return true;
for(int i = 0; i < ikinds; ++i)
{
if(kcount[i] == 0)
continue ;
if(iPos % n)//如果该位置不是最左边
if(Graph[iTable[iPos-1]][1] != Graph[i][3])
continue ;
if(iPos >= n)//如果该位置不是在最上方一行
if(Graph[iTable[iPos-n]][2] != Graph[i][0])
continue ;
kcount[i]--;
iTable[iPos] = i;
if(DFS(iPos+1))
return true;
kcount[i]++;//回溯时恢复现场
}
return false;
}
int main()
{
int iTop, iRight, iBottom, ileft;
int i, j, kcase = 1;
while(scanf("%d", &n) && n)
{
if(kcase > 1)
printf("\n");
ikinds = 0;
for(i = 0; i < n*n; ++i)
{
scanf("%d %d %d %d", &iTop, &iRight, &iBottom, &ileft);
for(j = 0; j < ikinds; ++j)//查找输入的方块中是否有相同的类型
{
if(Graph[j][0] == iTop && Graph[j][1] == iRight && Graph[j][2] == iBottom && Graph[j][3] == ileft)
{
kcount[j]++;
break;
}
}
if(j == ikinds)//没有相同的类型
{
Graph[j][0] = iTop;
Graph[j][1] = iRight;
Graph[j][2] = iBottom;
Graph[j][3] = ileft;
kcount[j] = 1;
ikinds++;
}
}
if(DFS(0))
printf("Game %d: Possible\n", kcase++);
else
printf("Game %d: Impossible\n", kcase++);
}
return 0;
}