Luo Gu P1379 eight digital problem solution to a problem

My personal feeling is that a deformation bfs, or the master of the bfs bad people who have a certain degree of difficulty.

This question ideas:

Generally found with bfs, come with a weight map, where only one queue because less number of steps to achieve a certain state of the queue state before the number of steps more.

 1 #include<iostream>
 2 #include<cmath>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<map>
 6 #include<queue>
 7 using namespace std;
 8 long long dx[4]={-1,0,0,1};
 9 long long dy[4]={0,-1,1,0};
10 long long n;
11 int  main()
12 {
13     cin>>n;
14     queue<long long> q;
15     q.push(n);
16     map<long long,long long> m;
17     m[n]=0;
18     while(!q.empty())
19     {
20         int cnt=q.front(); 
21         int zyc[3][3],xx=0,yy=0,n=cnt;
22         q.pop();
23         if(cnt==123804765)break;
24         for(long long i=2;i>=0;i--)
25             for(long long j=2;j>=0;j--)
26             {
27                 zyc[i][j]=n%10;
28                 n/=10;
29                 if(!zyc[i][j])
30                 {
31                     xx=i;
32                     yy=j;
33                 }
34             }
35         for(long long i=0;i<4;i++)
36         {
37             long long nx=xx+dx[i],ny=yy+dy[i],ans=0;
38             if(nx<0||ny<0||nx>2||ny>2)continue;
39             swap(zyc[nx][ny],zyc[xx][yy]);
40             for(long long i=0;i<3;i++)
41                 for(long long j=0;j<3;j++)ans=ans*10+zyc[i][j];
42             if(!m.count(ans))
43             {
44                 m[ans]=m[cnt]+1;
45                 q.push(ans);
46             }
47             swap(zyc[nx][ny],zyc[xx][yy]);
48         }
49     }
50     cout<<m[123 804 765 ]; 
 51 is      return  0 ;
 52 is } 
please treatise big brother(Anyway, I do not know what that means treatise)

 

Guess you like

Origin www.cnblogs.com/handsome-zyc/p/11237371.html