2 1234 2144 1111 9999
2 4
//BFS,总共才10*10*10*10个状态,故不会超时!
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; char str1[10]; char str2[10]; struct node { char str[6]; int step; }; bool visited[10][10][10][10]; int bfs() { int i; queue<node>qq; memset(visited,0,sizeof(visited)); node a; strcpy(a.str,str1); // a.str=str1; a.step=0; qq.push(a); while(!qq.empty()) { a=qq.front(); qq.pop(); for(i=0;i<4;i++) { if(a.str[i]==str2[i]) continue; else break; } if(i>=4) return a.step; node b; for(i=0;i<4;i++) { strcpy(b.str,a.str); b.step=a.step+1; b.str[i]=a.str[i]+1; if(b.str[i]-'0'==10) b.str[i]='1'; if(!visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']) { visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']=true; qq.push(b); } } for(i=0;i<4;i++) { strcpy(b.str,a.str); b.step=a.step+1; b.str[i]=a.str[i]-1; if(b.str[i]-'0'==0) b.str[i]='9'; if(!visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']) { visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']=true; qq.push(b); } } for(i=0;i<3;i++) { b.step=a.step+1; strcpy(b.str,a.str); char ch=b.str[i]; b.str[i]=b.str[i+1]; b.str[i+1]=ch; if(!visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']) { visited[b.str[0]-'0'][b.str[1]-'0'][b.str[2]-'0'][b.str[3]-'0']=true; qq.push(b); } } } } int main() { int t; cin>>t; while(t--) { scanf("%s",str1); scanf("%s",str2); cout<<bfs()<<endl; } return 0; }