在一个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”。
现在,给你一个初始网格,请你通过最少的移动次数,得到正确排列。
输入格式
输入占一行,将3×3的初始网格描绘出来。
例如,如果初始网格如下所示:
1 2 3
x 4 6
7 5 8
则输入为:1 2 3 x 4 6 7 5 8
输出格式
输出占一行,包含一个字符串,表示得到正确排列的完整行动记录。如果答案不唯一,输出任意一种合法方案即可。
如果不存在解决方案,则输出”unsolvable”。
输入样例:
2 3 4 1 5 x 7 6 8
输出样例
ullddrurdllurdruldr
难度: 中等 |
时/空限制: 1s / 64MB |
总通过数: 384 |
总尝试数: 815 |
来源: 《算法竞赛进阶指南》 |
算法标签 |
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#define f(i,l,r) for(i=(l);i<=(r);i++)
#define d first
#define se second
using namespace std;
typedef pair<int, string> PIS;
string st, ed = "12345678x", pd;
int num;
priority_queue<PIS, vector<PIS>, greater<PIS> > q;
unordered_map<string, int> dis;
unordered_map<string, pair<char, string> > pre;
int dx[] = {-1, 0, 0, 1};
int dy[] = {0, 1, -1, 0};
char op[] = {'u', 'r', 'l', 'd'};
int h(string s)
{
int i, res = 0;
f(i, 0, 8){
if(s[i] != 'x'){
int t = s[i] - '1';
res += abs(i / 3 - t / 3) + abs(i % 3 - t % 3);
}
}
return res;
}
string bfs()
{
int i;
q.push({h(st), st});
dis[st] = 0;
while(!q.empty()){
PIS tmp = q.top();
q.pop();
if(tmp.se == ed) break;
int pos = tmp.se.find('x');
int x = pos / 3, y = pos % 3;
f(i, 0, 3){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || nx > 2 || ny < 0 || ny > 2) continue;
string s = tmp.se;
swap(s[pos], s[nx * 3 + ny]);
if(dis[s] == 0 || dis[s] > dis[tmp.se] + 1){
dis[s] = dis[tmp.se] + 1;
pre[s] = {op[i], tmp.se};
q.push({h(s) + dis[s], s});
}
}
}
string res, s = ed;
while(s != st){
res += pre[s].first;
s = pre[s].se;
}
reverse(res.begin(), res.end());
return res;
}
int main()
{
int i, j;
f(i, 1, 9){
string ch;
cin >> ch;
st += ch;
if(ch != "x") pd +=ch;
}
f(i, 0, 7){
f(j, i + 1, 7){
if(pd[i] > pd[j]) num ++;
}
}
if(num & 1) cout << "unsolvable" << endl;
else cout << bfs() << endl;
return 0;
}