思路是BFS,其实是个隐式图搜索的问题,同时需要存路径。可以正着搜,同时用一个数组p pp存每个状态是由哪个状态转移过来的(同时还要记录具体是用了哪个操作转移过来的),最后返回路径的时候从终点向前找,然后逆序一下。至于要输出字典序最小的操作序列,只需要在BFS的时候按字典序从小到大枚举操作即可(可以简单证明一下。首先BFS确实能搜到最短路,其次,如果存在字典序更小的路径,那么考虑该路径与算法所得路径第一次不同的操作,这个操作的字典序一定比算法中的相同位置的操作更小,但是每个状态在入队的时候,是先进先出的,所以该操作所扩展出来的状态也会先入队,那么该操作所得路径第一次走到终点的时候必然会被上述算法记录下来,也就是说算法所得路径就是那个字典序更小的路径,这就矛盾了)
#include <cstring>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
char g[2][4];
unordered_map<string, pair<char, string>> pre; //记录操作路径
unordered_map<string, int> dist; //记录操作数
void set(string state) //构造矩阵
{
for (int i = 0; i < 4; i ++ ) g[0][i] = state[i];
for (int i = 7, j = 0; j < 4; i --, j ++ ) g[1][j] = state[i];
}
string get() //还原为一维
{
string res;
for (int i = 0; i < 4; i ++ ) res += g[0][i];
for (int i = 3; i >= 0; i -- ) res += g[1][i];
return res;
}
string move0(string state) // 将上下调换位置
{
set(state);
for (int i = 0; i < 4; i ++ ) swap(g[0][i], g[1][i]);
return get();
}
string move1(string state) //首位列调换位置
{
set(state);
int v0 = g[0][3], v1 = g[1][3];
for (int i = 3; i > 0; i -- )
{
g[0][i] = g[0][i - 1];
g[1][i] = g[1][i - 1];
}
g[0][0] = v0, g[1][0] = v1;
return get();
}
string move2(string state) //中间部分顺时针旋转
{
set(state);
int v = g[0][1];
g[0][1] = g[1][1];
g[1][1] = g[1][2];
g[1][2] = g[0][2];
g[0][2] = v;
return get();
}
int bfs(string start, string end)
{
if (start == end) return 0;
queue<string> q;
q.push(start);
dist[start] = 0;
while (!q.empty())
{
auto t = q.front();
q.pop();
string m[3];
m[0] = move0(t);
m[1] = move1(t);
m[2] = move2(t);
for (int i = 0; i < 3; i ++ ) //遍历操作
if (!dist.count(m[i]))
{
dist[m[i]] = dist[t] + 1; // 更新操作数
pre[m[i]] = {'A' + i, t}; // 储存路径
q.push(m[i]); //加入新状态(点)
if (m[i] == end) return dist[end];
}
}
return -1;
}
int main()
{
int x;
string start, end;
for (int i = 0; i < 8; i ++ )
{
cin >> x;
end += char(x + '0'); //初始化end
}
for (int i = 1; i <= 8; i ++ ) start += char('0' + i); //初始化
int step = bfs(start, end);
cout << step << endl;
string res;
while (end != start)
{
res += pre[end].first; //将操作路径跟新为答案
end = pre[end].second; //回溯end直到end == start
}
reverse(res.begin(), res.end()); //将res倒置
if (step > 0) cout << res << endl;
return 0;
}