题目大意:给出一些拼图的碎片,要求判断是否能组成一个矩形,对于碎片,F表示平面,I表示凸面,O表示凹面,对于矩形,边必须为平, 并且碎片相连只能是以IO形式
解题思路:回溯+剪枝
剪枝1:在DFS前如果凹凸不等或F数量不等周长就直接输出NO
剪枝2:排序,在判断是否放置当前拼图的时候如果不可以放置,和他一样的不用再判断一次
剪枝3:在递归完成后如果已经成功就直接return
#include <cstdio>
#include <cstring>
#include <algorithm>
char pi[36][5], data[6][6][5];
int num, vis[40], row, col;
int cmp(const void*a, const void*b) {
return strcmp((char*)a, (char*)b);
}
bool judge(int x, int y, int i) {
if (x == 0 && pi[i][0] != 'F'|| y == 0 && pi[i][3] != 'F' || y == col - 1 && pi[i][1] != 'F' || x != row - 1 && pi[i][2] == 'F')
return false;
if ((x != 0 && pi[i][0] + data[x - 1][y][2] != 'I' + 'O') || (y != 0 && pi[i][3] + data[x][y - 1][1] != 'I' + 'O'))
return false;
return true;
}
bool DFS(int x, int y, int cur) {
if (cur == num)
return true;
char temp[5] = {0};
for (int i = 0; i < num; i++)
if (!vis[i] && strcmp(temp, pi[i]) && judge(x, y, i)) {
strcpy(temp, pi[i]);
strcpy(data[x][y], pi[i]);
vis[i] = 1;
if (DFS((cur + 1) / col, (cur + 1) % col, cur + 1))
return true;
vis[i] = 0;
}
return false;
}
int main() {
while (scanf("%d%d\n", &row, &col), num = row * col) {
int edge[120] = {0};
for (int i = 0; i < num; i++) {
scanf("%s", pi[i]);
for (int j = 0; j < 4; j++)
edge[pi[i][j]]++;
}
qsort(pi, num, sizeof(pi[0]), cmp);
memset(vis, 0, sizeof(vis));
printf(edge['F'] == 2 * (row + col) && edge['I'] == edge['O'] && DFS(0, 0, 0) ? "YES\n" : "NO\n");
}
return 0;
}