题目链接:https://www.luogu.org/problemnew/show/P2324
一个比较直接的思路是bfs爆搜,但这样只能拿20分,所以考虑优化。
在测试样例时能够看到深度为7的时候很快就跑出来了,在结合本题最大深度是15,所以可以用双向bfs来优化,即从两边各跑7或8的深度,最后用map合并,有点类似折半搜索。另外有一些需要注意的小细节已经在代码中注释。
code:
#include<iostream>
#include<map>
#include<queue>
#include<string>
using namespace std;
struct state {
int x, y;
string s;
};
map<string, int> M;
int t;
int dx[8]={1, 1, -1, -1, 2, 2, -2, -2}, dy[8]={2, -2, 2, -2, 1, -1, 1, -1};
string aim="111110111100*110000100000";
bool bfs(int x, int y, string s) {
queue<state> Q;
Q.push(state{x, y, s});
M[s]=1;
while (!Q.empty()) {
state u=Q.front();
Q.pop();
if (M[u.s]==8) break;
if (u.s==aim) {
cout << M[u.s]-1 << endl;
return true;
}
for (int i=0; i<8; i++) {
int xx=u.x+dx[i], yy=u.y+dy[i];
if (xx<1 || xx>5 || yy<1 || yy>5) continue;
string tmp=u.s;
int tmp1=(u.x-1)*5+u.y, tmp2=(xx-1)*5+yy;
char tmp_c=tmp[tmp1-1];
tmp[tmp1-1]=tmp[tmp2-1];
tmp[tmp2-1]=tmp_c;
if (M[tmp]==0) {
M[tmp]=M[u.s]+1;
Q.push(state{xx, yy, tmp});
}
}
}
return false;
}
void bfss(int x, int y, string s) {
queue<state> Q;
map<string, int> MS;//这个MS是用来防止走回去的,因为我们如果只靠M来判是不行的
M[s]=1;
Q.push(state{x, y, s});
MS[s]=true;
while (!Q.empty()) {
state u=Q.front();
Q.pop();
if (M[u.s]==9) {
cout << "-1" << endl;
return ;
}
for (int i=0; i<8; i++) {
int xx=u.x+dx[i], yy=u.y+dy[i];
if (xx<1 || xx>5 || yy<1 || yy>5) continue;
string tmp=u.s;
int tmp1=(u.x-1)*5+u.y, tmp2=(xx-1)*5+yy;
char tmp_c=tmp[tmp1-1];
tmp[tmp1-1]=tmp[tmp2-1];
tmp[tmp2-1]=tmp_c;
if (M[tmp]!=0 && !MS[tmp]) {
cout << M[tmp]-1+M[u.s] << endl;
return ;
}
if (!MS[tmp]) {
M[tmp]=M[u.s]+1;
Q.push(state{xx, yy, tmp});
MS[tmp]=true;
}
}
}
}
int main() {
cin >> t;
while (t--) {
M.clear();
string tmp, s="";
int x, y;
for (int i=1; i<=5; i++) {
cin >> tmp;
for (int j=0; j<5; j++) {
if (tmp[j]=='*') {
x=i, y=j+1;
}
}
s+=tmp;
}
if (!bfs(x, y, s)) bfss(3, 3, aim);
}
return 0;
}
PS:本题好像还可以用A*或者IDA*来解。
简单来说下:A*的估价函数就是当前我们已走步数加上剩余未归位的骑士-1的个数(乐观估计,-1是因为将空格也看在内了,而有空格在乐观估计的情况下就会出现一步使空格和骑士都归位的情况),若这个数值大于15的话,那么就不合法。
IDA*就是在限制深度喽, 这样可以在整个搜索树深度很大而答案深度又很小的情况下大大提高效率。