题目描述
在一个3×3的网格中,1~8这8个数字和一个“X”恰好不重不漏地分布在这3×3的网格中。
例如:
1 2 3
X 4 6
7 5 8
在游戏过程中,可以把“X”与其上、下、左、右四个方向之一的数字交换(如果存在)。
我们的目的是通过交换,使得网格变为如下排列(称为正确排列):
1 2 3
4 5 6
7 8 X
例如,示例中图形就可以通过让“X”先后与右、下、右三个方向的数字交换成功得到正确排列。
交换过程如下:
1 2 3 1 2 3 1 2 3 1 2 3
X 4 6 4 X 6 4 5 6 4 5 6
7 5 8 7 5 8 7 X 8 7 8 X
把“X”与上下左右方向数字交换的行动记录为“u”、“d”、“l”、“r”。
现在,给你一个初始网格,请你通过最少的移动次数,得到正确排列。
样例
输入样例:
2 3 4 1 5 x 7 6 8
输出样例
ullddrurdllurdruldr
算法1
(A*)
首先,需要对可行解进行判断,如果当前状态和最终排好序的状态 逆序数不相同,则输出无解。
假如问题有解,那么采用$A^*$算法。估价函数$f(state)$表示当前state
状态 距离最终排好序的状态的曼哈顿距离。
因为每次只会移动一步,距离只会增加1,所以可以采用bfs() + 优先队列搜索。
当搜索结束的时候,就是最小的步数。
时间复杂度
参考文献
C++ 代码
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <cmath>
#include <queue>
using namespace std;
#define x first
#define y second
typedef pair<int, string> PIS;
int f(string state){
int res = 0;
for (int i = 0; i < 9; i ++ ){
if (state[i] != 'x'){
int v = state[i] - '1';
res += abs(v / 3 - i / 3) + abs(v % 3 - i % 3);//i / 3, i % 3表示排好序的八数码数字应该所在的位置
}
}
return res;
}
string bfs(string start){
int dx[4] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
char op[5] = "urdl";
string end = "12345678x";
unordered_map<string, int> dist;
unordered_map<string, pair<char, string>> pre;
priority_queue<PIS, vector<PIS>, greater<PIS>> heap;
heap.push({f(start), start});
dist[start] = 0;
while (heap.size()){
auto t = heap.top(); heap.pop();
string state = t.y;
if (state == end) break;
int x, y;
//找到'x'所在的位置
for (int i = 0; i < 9; i ++ )
if (state[i] == 'x'){
x = i / 3, y = i % 3;
break;
}
string source = state;//由于需要进行四次交换,所以保存现场。
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) continue;
state = source;
swap(state[x * 3 + y], state[a * 3 + b]);
if (dist.count(state) == 0 || dist[state] > dist[source] + 1){
dist[state] = dist[source] + 1;
pre[state] = {op[i], source};
heap.push({dist[state] + f(state), state});
}
}
}
string res;
while (end != start){
res += pre[end].x;
end = pre[end].y;
}
reverse(res.begin(), res.end());
return res;
}
int main(){
string start, seq;
char c;
while (cin >> c){
start += c;
if (c != 'x') seq += c;
}
int cnt = 0;
for (int i = 0; i < 8; i ++ )
for (int j = i + 1; j < 8; j ++ )
if (seq[i] > seq[j]) cnt ++;
if (cnt % 2) puts("unsolvable");
else cout << bfs(start) << endl;
return 0;
}