搜索------Catch That Cow
从一个点a走到另一个点b,中间可以经过x+1,x-1,x*2,最少几步可以到达b点
-------------------------------------------------------------------------------------
#include<stdio.h> #include<string.h> #include<algorithm> #include<queue> #include<stack> char str[105][105]; int dir[8][2] = {{1,1},{-1,1},{-1,-1},{1,-1}}; int n,k; int a = 0; using namespace std; struct point { int n,m; }; int oo[111111]; int check(int n) { if(n>=0&&n<=100000&&(!oo[n])) return 1; return 0; } int dfs(int x) { queue<point>Q; point now,next; now.n = x; now.m = 0; oo[x] = 1; Q.push(now); while(!Q.empty()) { now = Q.front(); Q.pop(); if(now.n == k) { return now.m; } next.n = now.n + 1; if(check(next.n)) { oo[next.n] = 1; next.m = now.m+1; Q.push(next); } next.n = now.n - 1; if(check(next.n)) { oo[next.n] = 1; next.m = now.m + 1; Q.push(next); } next.n = now.n * 2; if(check(next.n)) { oo[next.n] = 1; next.m = now.m + 1; Q.push(next); } } return -1; } int main() { while(~scanf("%d%d",&n,&k)) { memset(oo,0,sizeof(oo)); int ans = dfs(n); printf("%d\n",ans); } return 0; }