1152: 棋盘变换 [搜索]
时间限制: 1 Sec 内存限制: 128 MB
题目描述
给定一个4*4的01棋盘,1代表棋子,0代表空格,棋子1每次可以移动到相邻上下左右四个位置的空格。然后再给定你目标棋盘,问你最少在多少步能把当前棋盘变成目标棋盘状态。
输入
第一行输入一个整数T,代表有T组测试数据。接下来给出只有0和1的4*4的当前棋盘和4*4的目标棋盘,中间有一个空行。
输出
输出一个整数表示最小的步数,若不能到达输出-1。
样例输入
1
0001
0011
1100
1111
1011
1101
0000
1101
样例输出
8
思路:
预处理两张图不同的位置,如果个数不同,输出-1;如果相等,把两张图的位置暴力组合,求出最小的步数,最差的情况为T * pow(8, 8)。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int MAXN = 1e5 + 10;
char str1[5][5], str2[5][5];
int mapp1[5][5], mapp2[5][5];
bool vis[20];
int p1, p2, ans;
struct node {
int x;
int y;
}s1[20], s2[20];
void dfs(int p, int dis) {
// printf("%d %d\n", p, dis);
if(p == p1) {
ans = min(ans, dis);
return;
}
int res1 = s1[p].x;
int res2 = s1[p++].y;
for(int i = 0; i < p2; i++) {
if(vis[i]) continue;
vis[i] = 1;
int ant = 0;
int cnt1 = s2[i].x;
int cnt2 = s2[i].y;
ant = dis + abs(res1 - cnt1) + abs(res2 - cnt2);
dfs(p, ant);
vis[i] = 0;
}
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
memset(vis, 0, sizeof(vis));
memset(mapp1, 0, sizeof(mapp1));
memset(mapp2, 0, sizeof(mapp2));
memset(s1, 0, sizeof(s1));
memset(s2, 0, sizeof(s2));
for(int i = 1; i <= 4; i++) {
getchar();
for(int j = 1; j <= 4; j++) {
scanf("%c", &str1[i][j]);
mapp1[i][j] = str1[i][j] - '0';
}
}
getchar();
for(int i = 1; i <= 4; i++) {
getchar();
for(int j = 1; j <= 4; j++) {
scanf("%c", &str2[i][j]);
mapp2[i][j] = str2[i][j] - '0';
}
}
p1 = 0, p2 = 0, ans = 1e8;
for(int i = 1; i <= 4; i++) {
for(int j = 1; j <= 4; j++) {
if(mapp1[i][j] + mapp2[i][j] == 2) {
mapp1[i][j] = 0;
mapp2[i][j] = 0;
}
else if(mapp1[i][j]) {
s1[p1].x = i;
s1[p1++].y = j;
// printf("1 -> %d %d\n", i, j);
}
else if(mapp2[i][j]) {
s2[p2].x = i;
s2[p2++].y = j;
// printf("2 -> %d %d\n", i, j);
}
}
}
if(p1 != p2) {
printf("-1\n");
continue;
}
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}