C++ 代码
最简单直白(菜)的写法。
#include <bits/stdc++.h>
using namespace std;
int ans = 0;
int main() {
ios :: sync_with_stdio(false);
cin.tie(0);
string temp = "";
string str = "";
getline(cin,temp); str+=temp;
getline(cin,temp); str+=temp;
int ay = 0,by = 0,ky = 0,kb=0;
for(int i = 0 ; i < str.size();i++){
if (str[i] == 'A')ay = i;
if (str[i] == 'B')by = i;
if (str[i] == ' ')ky = i;
}
queue<string> que,next;
queue<int> prq;
map<string, int> mp;
mp[str]++;
prq.push(ky);
que.push(str);
while (1){
if (que.empty())
{
ans++;
swap(que, next);
//cout<<'*'<<que.size()<<'*'<<ans<<endl;
}
str = que.front();
kb = prq.front();
if (kb<3){
swap(str[kb], str[kb+3]);
if (str[ay] == 'B' && str[by] == 'A')
break;
if (!mp[str])
{
kb+=3;
prq.push(kb);
next.push(str);
mp[str]++;
kb-=3;
}
swap(str[kb], str[kb+3]);
}
if(kb>2){
swap(str[kb], str[kb-3]);
if (str[ay] == 'B' && str[by] == 'A')
break;
if (!mp[str])
{
kb-=3;
prq.push(kb);
next.push(str);
mp[str]++;
kb+=3;
}
swap(str[kb], str[kb-3]);
}
if(kb == 0 || kb == 1 || kb == 3 || kb == 4){
swap(str[kb], str[kb+1]);
if (str[ay] == 'B' && str[by] == 'A')
break;
if (!mp[str])
{
kb+=1;
prq.push(kb);
next.push(str);
mp[str]++;
kb-=1;
}
swap(str[kb], str[kb+1]);
}
if(kb == 2 || kb == 1 || kb == 5 || kb == 4){
swap(str[kb], str[kb-1]);
if (str[ay] == 'B' && str[by] == 'A')
break;
if (!mp[str])
{
kb-=1;
prq.push(kb);
next.push(str);
mp[str]++;
kb+=1;
}
swap(str[kb], str[kb-1]);
}
que.pop();
prq.pop();
}
cout<<ans+1;
return 0;
}