初见安~这里是传送门:洛谷P2324
Description
在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位。在任何时候一个骑士都能按照骑
士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标相差为2,纵坐标相差为1的格子)移动到空
位上。 给定一个初始的棋盘,怎样才能经过移动变成如下目标棋盘: 为了体现出骑士精神,他们必须以最少的步
数完成任务。
Input
第一行有一个正整数T(T<=10),表示一共有N组数据。接下来有T个5×5的矩阵,0表示白色骑士,1表示黑色骑
士,*表示空位。两组数据之间没有空行。
Output
对于每组数据都输出一行。如果能在15步以内(包括15步)到达目标状态,则输出步数,否则输出-1。
Sample Input
2
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
Sample Output
7
-1
Sol
本人初学A*算法,也就只能来刷这些水题了QwQ
本题想要爆搜bfs估计是可以的吧。就是特别特别耗时耗内存。毕竟八数码3*3都要8000ms+,这个5*5就不好说了。
相信做过八数码的小伙伴都可以看出来这个题和八数码的思路其实是一 模 一 样 的!!!用IDA*枚举步数搜索状态,估价函数定义为该状态与目标状态相比不在正确位置上的点的数量,直接搜就可以了。
顺便也得到了一个很深的教训——用了ios::sync_with_stdio(false)过后一定不能cin/cout和scanf/printf混用QwQ本地测出来完全没问题,一交就惊起WA一片……
下面上代码……
#include<bits/stdc++.h>
using namespace std;
int t, k;//zero white one black
int ans[6][6] = {{0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1}, {0, 0, 1, 1, 1, 1}, {0, 0, 0, -1, 1, 1}, {0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0}};
int dir[8][2] = {{2, -1}, {2, 1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {-2, -1}, {-2, 1}};
int a[6][6];
bool judge = 0;
char tmp;
bool check()
{
for(int i = 1; i <= 5; i++)
for(int j = 1; j <= 5; j++)
if(a[i][j] != ans[i][j]) return false;
return true;
}
bool text(int now)//从某种作用上说,如果text返回的是cnt的话那就也可以当成check来用
{
int cnt = 0;
for(int i = 1; i <= 5; i++)
for(int j = 1; j <= 5; j++)
if(a[i][j] != ans[i][j])
if(++cnt + now > k) return false;//中途返回的话也算是一个优化啊。
return true;
}
bool in(int x, int y) {return 0 < x && x < 6 && 0 < y && y < 6;}//越界判定
void A_star(int now, int x, int y, int pre)
{
if(now == k) {if(check()) judge = true; return;}
for(int i = 0; i < 8; i++)
{
if(judge) return;//有解了
register int tx = x + dir[i][0], ty = y + dir[i][1];
if(!in(tx, ty) || pre + i == 7) continue;//pre和i是dir的顺序的应用之地——剪枝确保不走回头路
swap(a[x][y], a[tx][ty]);
if(text(now) && !judge) A_star(now + 1, tx, ty, i);
swap(a[x][y], a[tx][ty]);
}
}
int main()
{
// ios::sync_with_stdio(false);
scanf("%d", &t);
while(t--)
{
register int x, y;
for(int i = 1; i <= 5; i++)
for(int j = 1; j <= 5; j++)
{
cin >> tmp;//用scanf会读入换行符之类的,就直接用cin了。
a[i][j] = tmp - '0';
if(tmp == '*') a[i][j] = -1, x = i, y = j;//-1作为空格
}
if(check()) {puts("0"); continue;}//特判一下
k = 0, judge = 0;//多组数据,记得清空
while(++k <= 15)
{
A_star(0, x, y, -1);
if(judge) {printf("%d\n", k); break;}
}
if(!judge) puts("-1");
}
}
我这板子代码QAQ
迎评:)
——End——