用 BFS。

思路

  • 我们可以使用一个长度为 $3\times3$ 的 string 来表示状态,每一种状态可以进行旋转(左上,右上,左下,右下)。
  • 我们可以用 map 来记录状态。
  • 预处理一下即可。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<bits/stdc++.h>
#define int long long
using namespace std;
map<string,int> mp; int T,n; char c;
signed main(){
cin>>T; queue<string> q; //bfs
q.push("123456789"),mp["123456789"]=1;
while(q.size()){
string u=q.front(),v[4]={u,u,u,u}; q.pop();
v[3][4]=u[5],v[3][5]=u[8],v[3][7]=u[4],v[3][8]=u[7];
v[2][3]=u[4],v[2][4]=u[7],v[2][6]=u[3],v[2][7]=u[6];
v[1][1]=u[2],v[1][2]=u[5],v[1][4]=u[1],v[1][5]=u[4];
v[0][0]=u[1],v[0][1]=u[4],v[0][3]=u[0],v[0][4]=u[3];
for(int i=0;i<4;i++) if(!mp[v[i]]){
mp[v[i]]=mp[u]+1;if(v[i]=="0123456789")break;q.push(v[i]);
}
}while(T--){
string s;
for(int i=0;i<9;i++) cin>>c,s+=c;
cout<<mp[s]-1<<'\n';
}return 0;
}