题意:
八数码问题。
解析:
直接康拓展开state,化成一个类似hash的key。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1
using namespace std;
/// 0! 1! 2! 3! 4! 5! 6! 7! 8! 9!
int fac[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int dir[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char index[] = "udlr";
bool vis[362880];
int cantor(int s[])
{
int ret = 0;
for (int i = 0; i < 9; i++)
{
int cnt = 0;
for (int j = i + 1; j < 9; j++)
{
if (s[j] < s[i])
{
cnt++;
}
}
ret += (cnt * fac[9 - i - 1]);
}
return ret + 1;
}
struct Node
{
int state[9];
int pos; //0的位置
int key; //hash的key
string path;
} now, Next;
string ansPath;
int goal = 46234; // 123456780 cantor展开对应的key
bool bfs()
{
memset(vis, false, sizeof(vis));
queue<Node> q;
q.push(now);
vis[now.key] = true;
while (!q.empty())
{
now = q.front();
q.pop();
if (now.key == goal)
{
ansPath = now.path;
return true;
}
int x = now.pos / 3;
int y = now.pos % 3;
for (int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (0 <= nx && nx < 3 && 0 <= ny && ny < 3)
{
Next = now;
Next.pos = nx * 3 + ny;
Next.state[now.pos] = Next.state[Next.pos];
Next.state[Next.pos] = 0;
Next.key = cantor(Next.state);
// cout << now.key << endl;
if (!vis[Next.key])
{
vis[Next.key] = true;
Next.path = Next.path + index[i];
q.push(Next);
}
}
}
}
return false;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
char c[2];
while (~scanf("%s", c))
{
if (c[0] == 'x')
{
now.state[0] = 0;
now.pos = 0;
}
else
{
now.state[0] = c[0] - '0';
}
for (int i = 1; i < 9; i++)
{
scanf("%s", c);
if (c[0] == 'x')
{
now.state[i] = 0;
now.pos = i;
}
else
{
now.state[i] = c[0] - '0';
}
}
now.key = cantor(now.state);
ansPath = "";
if (bfs())
cout << ansPath << endl;
else
printf("unsolvable\n");
}
return 0;
}