使用BFS的不一定是在地图上移动,关键点在于状态的扩展
1107. 魔板
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#define x first
#define y second
#define ST pair<string, int>
using namespace std;
string start_st = "12345678";
string end_st = "";
map<string, ST> pre;
map<string, bool> st;
string cmd(int k, string p)
{
if(k == 1)
{
reverse(p.begin(), p.end());
return p;
}
if(k == 2)
{
char t1 = p[3];
char tn = p[4];
return t1 + p.substr(0, 3) + p.substr(5,3) + tn;
}
if(k == 3)
{
char t2 = p[1];
p[1] = p[6];
p[6] = p[5];
p[5] = p[2];
p[2] = t2;
return p;
}
}
void bfs()
{
st[start_st] = true;
queue<string> q;
q.push(start_st);
while(!q.empty())
{
auto p = q.front();
q.pop();
int flag = 0;
for(int i = 1; i <= 3; i ++ )
{
string nx = cmd(i,p);
if(st[nx])continue;
st[nx] = true;
if(nx == end_st)flag = 1;
q.push(nx);
pre[nx].x = p;
pre[nx].y = i;
}
if(flag)break;
}
}
int main()
{
for(int i = 1; i <= 8; i ++ )
{
char t;
cin >> t;
end_st = end_st + t;
}
bfs();
string ans;
while(pre.count(end_st))
{
ans += char('A' + pre[end_st].y - 1);
end_st = pre[end_st].x;
}
cout << ans.size() << endl;
if(ans.size())
{
reverse(ans.begin(), ans.end());
cout << ans;
}
}