ZOJ 2416 Open the Lock

简单的广度优先搜索。我的代码很繁,不想简化想方法了。

 

#include<iostream> #include<cstdio> #include<cstring> #include<queue> struct node { int n; int ceng; } t,e;; int flag[10000]; int main(void) { std::queue<struct node> q; int cases,cha; int from,to; int g,s,b,qi; scanf("%d",&cases); while( cases-- ) { while( !q.empty() ) q.pop(); memset(flag,0,sizeof(flag)); scanf("%d%d",&from,&to); t.n =from;t.ceng=0; q.push(t);flag[from]=1; while( !q.empty() ) { e = q.front();q.pop(); if( e.n == to ) break; qi=e.n/1000;b=e.n/100%10;s=e.n%100/10;g=e.n%10; ////////////////////////////////////////////////// t = e; if( qi==1 ) t.n += 8000;else t.n -= 1000; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; if( b==1 ) t.n += 800;else t.n -= 100; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; if( s == 1) t.n += 80;else t.n -= 10; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; if( g==1) t.n += 8;else t.n -= 1; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} ////////////////////////////////////////////////// t = e; if( qi==9 ) t.n -= 8000;else t.n += 1000; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; if( b==9 ) t.n -= 800;else t.n += 100; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; if( s == 9) t.n -= 80;else t.n += 10; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; if( g==9) t.n -= 8;else t.n += 1; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} ////////////////////////////////////////////////// t = e; cha = qi-b;t.n += -1000*cha + 100*cha; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; cha = b-s;t.n += -100*cha + 10*cha; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} t = e; cha = s-g;t.n += -10*cha + 1*cha; if( !flag[t.n] ) {flag[t.n]=1;t.ceng++;q.push(t);} } printf("%d/n",e.ceng); } return 0; }  

你可能感兴趣的:(ZOJ 2416 Open the Lock)