POJ 3248 Catch That Cow
http://poj.org/problem?id=3278
二维BFS
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <queue> 5 #define READ() freopen("in.txt", "r", stdin); 6 7 using namespace std; 8 9 struct Loc 10 { 11 int x, step; 12 Loc () {} 13 Loc(int x, int step) : x(x), step(step) {} 14 }; 15 16 int N, K; 17 bool use[100007]; 18 bool OK(int x) 19 { 20 if (x < 0 || x > 100000 ) return false; 21 else return true; 22 } 23 int bfs() 24 { 25 queue<Loc> que; 26 que.push(Loc(N, 0)); 27 while (!que.empty()) 28 { 29 Loc crt = que.front(); 30 que.pop(); 31 if(use[crt.x]) continue; 32 use[crt.x] = true; 33 int nx = crt.x - 1; 34 if (OK(nx) && !use[nx]) 35 { 36 if (nx == K) return crt.step+1; 37 else que.push(Loc(nx, crt.step+1)); 38 } 39 nx = crt.x + 1; 40 if (OK(nx)) 41 { 42 if (nx == K && !use[nx]) return crt.step+1; 43 else que.push(Loc(nx, crt.step+1)); 44 } 45 nx = 2*crt.x; 46 if (OK(nx) && !use[nx]) 47 { 48 if (nx == K) return crt.step+1; 49 else que.push(Loc(nx, crt.step+1)); 50 } 51 } 52 } 53 int main() 54 { 55 //READ() 56 scanf("%d%d", &N, &K); 57 if (N == K) //有N == K的坑点 严谨一点 58 { 59 cout << 0 << endl; 60 return 0; 61 } 62 memset(use, 0, sizeof(use)); 63 int ans = bfs(); 64 cout << ans << endl; 65 return 0; 66 }