/*八数码的变形问题 本来是一个很简单的问题 可是我做的时候却出了些问题 导致久久不能AC。
int dy[]= {0,0,-1,1};
int dx[]= {-1,1,0,0};
这2个状态数组 如果改成int dx[]= {0,0,-1,1};
int dy[]= {-1,1,0,0}; 所出的结果跟正确结果不一样 // 当然 会同时改变 UDRL. 求大神解释..
*/
#include<cstdio>
#include<cstring>#include<map>
using namespace std;
const int M = 10000003;
typedef int State[10];
int head[M],next[M];
State st[M];
int path[M],pre[M];
int dy[]= {0,0,-1,1};
int dx[]= {-1,1,0,0};
char f[5] = "UDLR";
int hash(State s)
{
int v = 0;
for(int i = 0; i < 9; i++)
v = v*10+s[i];
return v%M;
}
int try_insert(int s)
{
int h = hash(st[s]);
for(int v = head[h]; v!=-1; v = next[v])
{
if(memcmp(st[v], st[s], sizeof(st[s])) == 0) return 0;
}
next[s] = head[h];
head[h] = s;
return 1;
}
int print(int m)
{
if(m)
{
print(pre[m]);
printf("%c",f[path[m]]);
}
}
int bfs()
{
memset(head,-1,sizeof(head));
memset(pre,0,sizeof(pre));
memset(path,0,sizeof(path));
int front=0,rear=1;
pre[0] = path[0] = -1;
try_insert(0);
while(front<rear)
{
State& s = st[front];
int z;
for(z = 0; z < 9; z++)
if(s[z]==0)
break;
int x = z/3,y = z%3;
for(int i = 0; i < 4; i++)
{
int nx = x+dx[i];
int ny = y+dy[i];
int nz = nx*3+ny;
if(nx>=0&&nx<3&&ny>=0&&ny<3)
{
State& t = st[rear];
memcpy(&t,&s,sizeof(s));
t[nz] = s[z];
t[z] = s[nz];
if(try_insert(rear))
{
path[rear]=i;
pre[rear]=front;
rear++;
}
}
}
front++;
}
return rear-1;
}
int main()
{
int t;
scanf("%d",&t);
for(int c=1; c<=t; c++)
{
for(int i = 0; i < 9; i++)
scanf("%d",&st[0][i]);
printf("Puzzle #%d\n",c);
int ans = bfs();
for(int i = 0; i < 9; i++)
{
printf("%d",st[ans][i]);
if(i%3==2)
printf("\n");
else printf(" ");
}
print(ans);
printf("\n\n");
}
return 0;
}