题目描述
强行以字典序最小顺序存储路径
算法1
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;
unordered_map<string, char> ans;
unordered_map<string, string> pre;
int bfs(string start, string end)
{
queue<string> q;
unordered_map<string, int> d;
q.push(start);
d[start] = 0;
int dx[4] = {1, 0, 0, -1}, dy[4] = {0, -1, 1, 0};
char cs[] = "dlru"; // 下左右上
while(q.size())
{
auto t = q.front();
q.pop();
int distance = d[t];
if(t == end) return distance;
int k = t.find('x');
int x = k / 3, y = k % 3;
pre[start] = "";
for(int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < 3 && b >= 0 && b < 3)
{
swap(t[k], t[a * 3 + b]);
if(d[t] == 0)
{
d[t] = distance + 1;
q.push(t);
swap(t[k], t[a * 3 + b]);
string aa = t;
swap(t[k], t[a * 3 + b]);
string bb = t;
pre[bb] = aa;
ans[bb] = cs[i];
}
swap(t[k], t[a * 3 + b]);
}
}
}
return -1;
}
int main ()
{
string start;
for(int i = 0; i < 9; i ++ )
{
char c;
cin >> c;
start += c;
}
string end = "12345678x";
int step = bfs(start, end);
if(step == -1) cout << "unsolvable" << endl;
else
{
string cnt = "";
while(end != start)
{
cnt += ans[end];
end = pre[end];
}
reverse(cnt.begin(), cnt.end());
cout << cnt << endl;
}
return 0;
}