Catch That Cow(BFS)

http://poj.org/problem?id=3278

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<queue>
 4 #define MAX 1000002
 5 using namespace std;
 6 int vis[MAX],step[MAX];
 7 int dir[3][2] = {{1,1},{1,-1},{2,0}};
 8 queue <int> q;
 9 int n,m;
10 void bfs(int s)
11 {
12     vis[s] = 1;
13     q.push(s);
14     while(!q.empty())
15     {
16         s = q.front();
17         q.pop();
18         for (int i = 0; i < 3; i ++)
19         {
20             int x = s*dir[i][0] + dir[i][1];
21             if(!vis[x] && x >= 0 && x < MAX)
22             {
23                 if(x==m)
24                 {
25                     step[x] = step[s] + 1;
26                     return ;
27                 }
28                 else
29                 {
30                     q.push(x);
31                     vis[x] = 1;
32                     step[x] = step[s] + 1;
33                 }
34             }
35         }
36     }
37 }
38 int main()
39 {
40     scanf("%d%d",&n,&m);
41     memset(vis,0,sizeof(vis));
42     memset(step,0,sizeof(step));
43     bfs(n);
44     printf("%d\n",step[m]);
45     return 0;
46 }
View Code

 

posted @ 2013-08-14 11:16  N_ll  阅读(209)  评论(0编辑  收藏  举报