题目大意:给出一些积木,要求将积木全部使用后拼成一个 4 * 4 的正方形
解题思路:将所有积木用结构体储存起来,然后在 4 * 4 的地图上逐一去判断。主要注意:
如果当前位置没有合适的积木可以放的话可以直接回溯了,因为题目要求是不能旋转
#include <cstdio>
int vis[4][4] = {0}, t = 0, n;
struct Piece {
int row;
int column;
char data[5][5];
} pie[20];
bool DFS(int cur) {
if (cur == n)
return true;
for (int i = 0; i <= 4 - pie[cur].row; i++)
for (int j = 0; j <= 4 - pie[cur].column; j++) {
bool ok = true;
for (int k = 0; k < pie[cur].row; k++)
for (int l = 0; l < pie[cur].column; l++)
if (!vis[k + i][l + j] && pie[cur].data[k][l] == '1')
vis[k + i][l + j] = cur + 1;
else if (vis[k + i][l + j] && pie[cur].data[k][l] == '1')
ok = false;
if (ok && DFS(cur + 1))
return true;
for (int k = 0; k < 4; k++)
for (int l = 0; l < 4; l++)
if (vis[k][l] == cur + 1)
vis[k][l] = 0;
}
return false;
}
int main() {
while (scanf("%d", &n), n) {
int sum = 0;
for (int i = 0; i < n; i++) {
scanf("%d%d\n", &pie[i].row, &pie[i].column);
for (int j = 0; j < pie[i].row; j++)
for (int k = 0; k < pie[i].column; k++) {
scanf(k == pie[i].column ? "%c" : "%c\n", &pie[i].data[j][k]);
sum += pie[i].data[j][k] - '0';
}
}
printf(t++ ? "\n" : "");
if (sum == 16 && DFS(0))
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
printf( j < 3 ? "%d" : "%d\n", vis[i][j] ), vis[i][j] = 0;
else
printf("No solution possible\n");
}
return 0;
}