|
- #include<iostream>
- using namespace std;
- int m[6][6]= {0,0,0,0,0,0,
- 0,1,1,1,1,1,
- 0,0,1,1,1,1,
- 0,0,0,-1,1,1,
- 0,0,0,0,0,1,
- 0,0,0,0,0,0,
- };///0白 1黑 2空格
- int i,j,t,x0,y0,a[6][6],ans;
- int dx[9]={0,-2,-2,-1,-1,1,1,2,2};
- int dy[9]={0,-1,1,-2,2,-2,2,-1,1};
- int done()///完成
- {
- int id,jd,s=0;
- for (id=1; id<=5; id++)
- for (jd=1; jd<=5; jd++)
- {
- if (a[id][jd]!=m[id][jd]) s++;
- }
- return s;
- }
- void dfs(int x,int y,int sum,int last)///(x,y)空格 sum步数
- {
- int don=done();
- if (sum+don>16) return;
- else if (sum>=ans) return;
- else if (don==0)
- {ans=min(ans,sum);return;}
- else
- for (int k=1; k<=8; k++)
- {
- int tx=x+dx[k];
- int ty=y+dy[k];
- if (1<=tx&&tx<=5&&1<=ty&&ty<=5&&(k+last)!=9)///可以搜索
- {
- swap(a[tx][ty],a[x][y]);
- dfs(tx,ty,sum+1,k);
- swap(a[tx][ty],a[x][y]);
- }
- }
- }
- int main()
- {
- cin>>t;
- for (int it=1; it<=t; it++)
- {
- ans=99999;
- for (i=1; i<=5; i++)
- {
- string s;
- cin>>s;
- for (j=1; j<=5; j++)
- {
- if (s[j-1]=='1') a[i][j]=1;
- else if (s[j-1]=='0') a[i][j]=0;
- else if (s[j-1]=='*')
- {
- a[i][j]=-1;
- x0=i;
- y0=j;
- }
- }
- }
- dfs(x0,y0,0,0);
- if (ans<=15) cout<<ans<<endl;
- else cout<<"-1"<<endl;
- }
- return 0;
- }
复制代码 |
|