参考《算法设计与分析》P276
#include <iostream>
#include <string>
using namespace std;
int map[25][4];
int n;
int q;
int icount[25];
int itable[25];
int place(int pos)
{
if (pos == n*n)return 1; //递归出口
for (int i = 0; i < q; i++) //在pos位置上,从候选类型中选择一个放在此位置
{
if (icount[i] == 0)continue; //如果类型为i的没有,则继续for循环
if (pos%n != 0)
if (map[itable[pos - 1]][1] != map[i][3])continue;
if (pos >= n)
if (map[itable[pos - n]][2] != map[i][0])continue;
itable[pos] = i;
icount[i]--;
if (place(pos + 1) == 1)return 1;
icount[i]++;
}
return 0;
}
int main()
{
while (cin >> n && n)
{
int top, right, down, left;
/*
初始化全局变量
*/
q = 0;
memset(map, 0, sizeof(map));
memset(icount, 0, sizeof(icount));
memset(itable, 0, sizeof(itable));
/*
输入值,重复类型不存入map中
*/
for (int i = 0; i < n*n; i++)
{
cin >> top >> right >> down >> left;
int j;
for ( j = 0; j < q; j++)
{
if (map[j][0] == top && map[j][1] == right && map[j][2] == down && map[j][3] == left)
{
icount[j]++;
break;
}
}
if (j == q)
{
map[j][0] = top;
map[j][1] = right;
map[j][2] = down;
map[j][3] = left;
icount[j]++;
q++;
}
}
/*
开始深搜+回溯
*/
if (place(0)) cout << "possible" << endl;
else cout << "impossible" << endl;
}
system("pause");
return 0;
}
此题也可以理解为:一个全排列+剪枝(条件处理)