HDU1195 BFS
题意:从一个4位数到另一个4位数 所需的步数
bfs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string> 3 #include<stdlib.h> 4 #include<queue> 5 #include<algorithm> 6 #include<iostream> 7 #include<map> 8 using namespace std; 9 const int maxn = 10; 10 char a[maxn],b[maxn]; 11 int vis[ 100000 ]; 12 struct node{ 13 char nn[maxn]; 14 int t; 15 }; 16 17 int solve( char a,char b,char c, char d ){ 18 return (a-'0')*1+(b-'0')*10+(c-'0')*100+(d-'0')*1000; 19 } 20 21 int bfs(){ 22 queue<node>q; 23 while( !q.empty() ) 24 q.pop(); 25 node now,next; 26 memset( vis,0,sizeof( vis )); 27 strcpy( now.nn,a );//now.nn=a; 28 vis[ solve(a[0],a[1],a[2],a[3]) ]=1; 29 now.t=0; 30 q.push( now ); 31 while( !q.empty() ){ 32 now=q.front(),q.pop(); 33 //printf("now:%s\n",now.nn); 34 if( solve(now.nn[0],now.nn[1],now.nn[2],now.nn[3]) == solve( b[0],b[1],b[2],b[3] ) ) 35 return now.t; 36 //next.nn=now.nn; 37 next.t=now.t+1; 38 for( int i=0;i<4;i++ ){ 39 strcpy( next.nn,now.nn );//.nn=now.nn; 40 if( next.nn[i]=='9' ){ 41 next.nn[i]='1'; 42 } 43 else{ 44 next.nn[i]=now.nn[i]+1; 45 } 46 if( vis[ solve(next.nn[0],next.nn[1],next.nn[2],next.nn[3]) ]==0/*mp[ next.nn ]==0*/ ){ 47 vis[ solve(next.nn[0],next.nn[1],next.nn[2],next.nn[3]) ]=1; 48 q.push( next ); 49 } 50 }//add 1 51 for( int i=0;i<4;i++ ){ 52 strcpy( next.nn,now.nn );//next.nn=now.nn; 53 if( next.nn[i]=='1' ){ 54 next.nn[i]='9'; 55 } 56 else{ 57 next.nn[i]=now.nn[i]-1; 58 } 59 if( vis[ solve(next.nn[0],next.nn[1],next.nn[2],next.nn[3]) ]==0/*mp[ next.nn ]==0*/ ){ 60 vis[ solve(next.nn[0],next.nn[1],next.nn[2],next.nn[3]) ]=1; 61 q.push( next ); 62 } 63 } 64 char tmp; 65 for( int i=1;i<4;i++ ){ 66 strcpy( next.nn,now.nn );//next.nn=now.nn; 67 tmp=now.nn[i]; 68 next.nn[i]=now.nn[i-1]; 69 next.nn[i-1]=tmp; 70 if( vis[ solve(next.nn[0],next.nn[1],next.nn[2],next.nn[3]) ]==0/*mp[ next.nn ]==0*/ ){ 71 vis[ solve(next.nn[0],next.nn[1],next.nn[2],next.nn[3]) ]=1; 72 q.push( next ); 73 } 74 } 75 } 76 return -1; 77 } 78 79 int main(){ 80 int ca; 81 scanf("%d",&ca); 82 while( ca-- ){ 83 scanf("%s%s",a,b); 84 int ans=bfs(); 85 printf("%d\n",ans); 86 } 87 return 0; 88 }
keep moving...