/*POJ 3278 Catch that Cow---simple BFS*/#include<cstdio>#include<queue>#include<cstring>using namespacestd;Const intMAXN =100005;BOOLVISIT[MAXN];intSTEP[MAXN];intBFsintNintk) { if(n = =k)return 0; memset (Visit,0,sizeofvisit); Queue<int> q;//on the node where the store is visited but the next point is to be judgedQ.push (n); Step[n]=0; Visit[n]=1; intX,next; while(!Q.empty ()) {x=Q.front (); Q.pop (); for(inti =0; I <3; ++i) { //i = 0,1,2 means wide search in different directions respectively if(i = =0) Next= X-1; Else if(i = =1) Next= x +1; ElseNext= x *2; //whether the judgment is crossed and whether it has been accessed if(Visit[next] | | Next <0|| Next >=MAXN)Continue; Visit[next]=1; Step[next]= Step[x] +1;//number of steps +1 if(Next = =k)returnStep[next]; Q.push (next); } //Q.pop (); } return-1; }intMain () {intN, K; while(SCANF ("%d%d", &n, &k) = =2) {printf ("%d\n", BFS (n, k)); } return 0;}
View Code
POJ 3278 Catch that Cow---simple BFS