DFS搜索,本题要剪枝。。不然必TLE,开始我天真地用毫无剪枝的代码直接超时了。。网上搜了搜都说要把完全相同的方块归为一类,这个搜索的时候才会比较快。。好坑啊,谁知道测试数据有这么多重复的方块。。修改之后提交AC了,不过时间还是用了近2s
#include<stdio.h>
#include<string.h>
static int n, find, total, a[5][5], v[25], up[25], right[25], down[25],
left[25];
int gnome(int index, int row, int col)
{
if (row - 1 >= 0 && a[row - 1][col] != -1
&& down[a[row - 1][col]] != up[index])
return 0;
if (col - 1 >= 0 && a[row][col - 1] != -1
&& right[a[row][col - 1]] != left[index])
return 0;
return 1;
}
void dfs1008(int depth)
{
if (depth == n * n)
find = 1;
if (find)
return;
int i, row = depth / n, col = depth % n;
for (i = 0; i < total; i++)
if (v[i] && gnome(i, row, col))
{
v[i]--;
a[row][col] = i;
dfs1008(depth + 1);
a[row][col] = -1;
v[i]++;
}
}
int main()
{
int count = 0;
while (scanf("%d", &n), n)
{
int i, j, t1, t2, t3, t4;
total = 0;
memset(a, -1, 5 * 5 * sizeof(int));
memset(v, 0, 25 * sizeof(int));
for (i = 0; i < n * n; i++)
{
scanf("%d %d %d %d", &t1, &t2, &t3, &t4);
for (j = 0; j < total; j++)
if (up[j] == t1 && right[j] == t2 && down[j] == t3
&& left[j] == t4)
break;
if (j == total)
{
up[total] = t1;
right[total] = t2;
down[total] = t3;
left[total] = t4;
total++;
}
v[j]++;
}
find = 0;
dfs1008(0);
if (count)
putchar('\n');
printf("Game %d: %s", ++count, find ? "Possible\n" : "Impossible\n");
}
return 0;
}