Open the Lock----hdu1195
对每一位都进行加1、减1、和相邻位交换操作。
故采用广搜, 直到可以打开为止。。。。。。。。
1 #include<iostream> 2 #include<cstring> 3 #include<queue> 4 using namespace std; 5 int s[4], e[4]; 6 bool v[10][10][10][10];//标记有没有被访问 7 struct node 8 { 9 int x[4]; 10 int tem; 11 }; 12 queue<node>qu; 13 node p, q; 14 int bfs() 15 { 16 memset( v, 0, sizeof(v) ); 17 while( qu.empty()!=1 )qu.pop(); 18 int i, j; 19 p.tem=0; 20 for( i=0; i<4; i++ ) 21 p.x[i]=s[i]; 22 qu.push(p); 23 while( qu.empty()!=1 ) 24 { 25 q=qu.front(); 26 qu.pop(); 27 int flag=0; 28 int temp; 29 for( i=0; i<4; i++ ) 30 { 31 if( q.x[i]!=e[i] ) 32 { 33 flag=1; 34 break; 35 } 36 } 37 if( flag==0 )return q.tem; 38 for( i=0; i<4; i++ )//每一位都加1 39 { 40 temp=q.x[i]; 41 if( q.x[i]==9 )q.x[i]=1; 42 else q.x[i]+=1; 43 if( !v[q.x[0]][q.x[1]][q.x[2]][q.x[3]] ) 44 { 45 v[q.x[0]][q.x[1]][q.x[2]][q.x[3]]=true; 46 for( j=0; j<4; j++ ) 47 p.x[j]=q.x[j]; 48 p.tem=q.tem+1; 49 qu.push(p); 50 } 51 q.x[i]=temp; 52 } 53 for( i=0; i<4; i++ )//每一位都减1 54 { 55 temp=q.x[i]; 56 if( q.x[i]==1 )q.x[i]=9; 57 else q.x[i]-=1; 58 if( !v[q.x[0]][q.x[1]][q.x[2]][q.x[3]] ) 59 { 60 v[q.x[0]][q.x[1]][q.x[2]][q.x[3]]=true; 61 for( j=0; j<4; j++ ) 62 p.x[j]=q.x[j]; 63 p.tem=q.tem+1; 64 qu.push(p); 65 } 66 q.x[i]=temp; 67 } 68 for( i=0; i<3; i++ )//从前往后交换相邻位 69 { 70 temp=q.x[i], q.x[i]=q.x[i+1], q.x[i+1]=temp; 71 if( !v[q.x[0]][q.x[1]][q.x[2]][q.x[3]] ) 72 { 73 v[q.x[0]][q.x[1]][q.x[2]][q.x[3]]=true; 74 for( j=0; j<4; j++ ) 75 p.x[j]=q.x[j]; 76 p.tem=q.tem+1; 77 qu.push(p); 78 } 79 temp=q.x[i], q.x[i]=q.x[i+1], q.x[i+1]=temp; 80 } 81 } 82 return -1; 83 } 84 int main() 85 { 86 int t; 87 int a, b; 88 cin >> t; 89 while( t-- ) 90 { 91 cin >> a >> b; 92 for( int i=0; i<4; i++ ) 93 { 94 s[i]=a%10, e[i]=b%10; 95 a/=10, b/=10; 96 } 97 cout << bfs() << endl; 98 } 99 return 0; 100 }
。

浙公网安备 33010602011771号