题目描述:
如果一个 3 × 3 的矩阵中,整数 1-9 中的每个都恰好出现一次,我们称这个矩阵为一个幻 方。
我们可以对一个幻方进行一些操作。具体来说,我们可以
• 选择幻方的一行,整体向右移动一格,并将最右侧的数字移到最左边;或者
• 选择幻方的一列,整体向下移动一格,并将最下侧的数字移到最上面。
例如,下面两个操作分别是一种合法的行操作和列操作:
显然,一个合法的幻方经过一次操作后一定还是合法的幻方。
给定幻方的初始状态,请问,最少要经过多少次变换,才能变成最终状态?
输入描述:
第一行一个整数 T (1 ≤ T ≤ 200000),表示测试用例的数量。
接下来有 T 组测试用例,每组测试用例前有一个空行。每组样例的前 3 行为幻方的初始状态,后 3 行为幻方的最终状态。每行的数字之间没有空格。
保证初始状态和最终状态都是合法的幻方。
输出描述:
对于每组测试用例在一行内输出一个整数,表示答案。如果不可能从起始状态转变为最终状态,输出 impossible。
样例输入:
复制
4
123
456
789
231
456
789
457
213
689
257
361
489
927
641
358
297
651
384
123
456
789
123
456
789
样例输出:
2
3
impossible
0
题目链接:http://acm.nyist.cf/web/contest/ranklist/cid/95
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<queue>
#include<iostream>
#include<map>
using namespace std;
int t,ji[150];
struct node
{
char str[5][5];
bool operator <(const node &b)const
{
for(int i=1; i<=3; i++)
for(int j=1; j<=3; j++)
{
if(this->str[i][j]!=b.str[i][j])
return this->str[i][j]<b.str[i][j];
}
return 0;
}
};
void see(node a)
{
for(int i=1; i<=3; i++)
{
for(int j=1; j<=3; j++)
{
printf("%c ",a.str[i][j]);
}
puts("");
}
puts("");
}
queue<node>q;
map<node,int>mp;
node run(node b,int f,int flag)
{
char c;
if(flag==0)
{
c=b.str[f][1];
b.str[f][1]=b.str[f][3];
b.str[f][3]=b.str[f][2];
b.str[f][2]=c;
}
else
{
c=b.str[1][f];
b.str[1][f]=b.str[3][f];
b.str[3][f]=b.str[2][f];
b.str[2][f]=c;
}
return b;
}
void dfs()
{
node a,b;
for(int i=1; i<=3; i++)
for(int j=1; j<=3; j++)
{
a.str[i][j]=j+(i-1)*3+'0';
}
mp[a]=1;
q.push(a);
while(!q.empty())
{
b=q.front();
q.pop();
for(int i=1; i<=3; i++)
{
a=run(b,i,0);
if(!mp[a])
{
mp[a]=mp[b]+1;
q.push(a);
}
a=run(b,i,1);
if(!mp[a])
{
mp[a]=mp[b]+1;
q.push(a);
}
}
}
return ;
}
int main()
{
dfs();
node a,b;
scanf("%d",&t);
while(t--)
{
for(int i=1;i<=3;i++)
scanf("%s",a.str[i]+1);
for(int i=1;i<=3;i++)
scanf("%s",b.str[i]+1);
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
ji[a.str[i][j]]=j+(i-1)*3+'0';
}
}
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
b.str[i][j]=ji[b.str[i][j]];
}
}
if(!mp[b])
printf("impossible\n");
else
printf("%d\n",mp[b]-1);
}
}