传送门UVa 10085 - The Most Distant State
类似八数码的题目,只不过要求输出的是最长步数的状态。
如何确定这个状态?
队列的最后一个状态就是,不过也不一定,说不定前几个状态也可以。
如何输出路径?
开一个father数组,用于记录每一个状态的父状态,一个path数组,记录父状态到当前状态的移动方向。
用递归的方法到达初始状态,然后顺序输出。
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 5000000;
const int dx[] = {-1, 1, 0, 0}; //上,下,左,右
const int dy[] = {0, 0, -1, 1};
const int HashSize = 10000003;
const char PathDir[5] = "UDLR"; //这里要和dir对应。
int head[HashSize], next[HashSize];
typedef int State[9];
State qu[MAXN], start, last;
int father[MAXN], path[MAXN], ans;
int TryToInsert(int s);
void BFS();
int Hash(State &s);
void PrintPath(int cur);
int main()
{
//freopen("input.txt", "r", stdin);
int T, i, j, cases = 1;
scanf("%d", &T);
while (T--)
{
for (i = 0; i < 9; i++)
scanf("%d", &start[i]);
BFS();
printf("Puzzle #%d\n", cases++);
for (i = 0; i < 3; i++)
printf("%d %d %d\n", qu[ans][i * 3], qu[ans][i * 3 + 1], qu[ans][i * 3 + 2]);
PrintPath(ans);
printf("\n\n");
}
return 0;
}
void BFS()
{
memset(head, 0, sizeof(head));
memcpy(qu[0], start, sizeof(start));
int front = 0, rear = 1;
while (front < rear)
{
State &s = qu[front];
//memcpy(last, s, sizeof(s));
int z;
for (z = 0; z < 9; z++)
if (!s[z])
break;
int x = z / 3, y = z % 3;
for (int d = 0; d < 4; d++)
{
int newx = x + dx[d];
int newy = y + dy[d];
int newz = newx * 3 + newy;
if (newx >= 0 && newx < 3 && newy >= 0 && newy < 3)
{
State &t = qu[rear];
memcpy(t, s, sizeof(s));
t[newz] = s[z];
t[z] = s[newz];
if (TryToInsert(rear))
{
father[rear] = front, path[rear] = d;
rear++;
}
}
}
front++;
}
ans = rear - 1;
}
int TryToInsert(int s)
{
int h = Hash(qu[s]);
int u = head[h];
while (u)
{
if (memcmp(qu[u], qu[s], sizeof(qu[s])) == 0)
return 0;
u = next[u];
}
next[s] = head[h];
head[h] = s;
return 1;
}
int Hash(State &s)
{
int v = 0;
for (int i = 0; i < 9; i++)
v = v * 10 + s[i];
return v % HashSize;
}
void PrintPath(int cur)
{
if (cur != 0)
{
PrintPath(father[cur]);
printf("%c", PathDir[path[cur]]);
}
}