简单广搜...set好用..恩. #include <cstdio> #include <iostream> #include <queue> #include <set> using namespace std; struct paipai{ int num; int step; }; queue<struct paipai>q; set<int> used; int a[5],b[5]; int T,from,to; void itoa(int n,int a[]) { for(int i=3;i>=0;i--) { a[i] = n%10; n/=10; } } int atoi(int a[]) { int sum = 0; for(int i=0;i<4;i++) { sum*=10; sum+=a[i]; } return sum; } void bfs() { used.clear(); used.insert(from); struct paipai now; now.num=from; now.step = 0; while(!q.empty()) q.pop(); q.push(now); now = q.front(); while(!q.empty()) { now= q.front(); q.pop(); if(now.num==to) { cout<<now.step<<endl; return ; } now.step++; for(int i=0;i<4;i++) { itoa(now.num,a); a[i]+=1; if(a[i]==10) a[i]=1; struct paipai tmp; tmp.num=atoi(a); tmp.step=now.step; if(!used.count(tmp.num)) { q.push(tmp); used.insert(tmp.num); } } for(int i=0;i<4;i++) { itoa(now.num,a); a[i]-=1; if(a[i]==0) a[i]=9; struct paipai tmp; tmp.num=atoi(a); tmp.step=now.step; if(!used.count(tmp.num)) { q.push(tmp); used.insert(tmp.num); } } for(int i=0;i<3;i++) { itoa(now.num,a); a[i]^=a[i+1]; a[i+1]^=a[i]; a[i]^=a[i+1]; struct paipai tmp; tmp.num=atoi(a); tmp.step=now.step; if(!used.count(tmp.num)) { q.push(tmp); used.insert(tmp.num); } } } } int main(void) { cin>>T; T=2; while(T--) { cin>>from>>to; //from = 1234;to = 2144; // from=1111;to=9999; bfs(); } return 0; }