hdu 1548A strange lift

http://acm.hdu.edu.cn/showproblem.php?pid=1548

之前用dfs写,,以为可以选择最小的,,当写到那时,就囧了,,不知道怎么处理。。或许真的可以用dfs只是可能要全部搜索才能判断。求路过的大牛指点一二dfs写法!

bfs写法:

View Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 int map[205];
 4 int vis[205];
 5 int queue[205];
 6 int rear,front;
 7 int count;
 8 int n;
 9 int bfs(int x,int y)
10 {
11     int top;
12     rear=0;
13     front=0;
14     
15     queue[rear++]=x;
16     vis[x]=1;
17     //if(x==y) return count;
18     while(rear>front)
19     {
20         
21         top=queue[front++];
22         if(top-map[top]>=1&&vis[top-map[top]]==0)
23         {
24             queue[rear++]=top-map[top];
25             vis[top-map[top]]=vis[top]+1;
26 
27         }
28         if(top+map[top]<=n&&vis[top+map[top]]==0)
29         {
30             queue[rear++]=top+map[top];
31             vis[top+map[top]]=vis[top]+1;
32         }
33         if(top==y) return vis[top]-vis[x];
34     }
35     return -1;
36 }
37 int main()
38 {
39     int a,b;
40     int i;
41     while(~scanf("%d",&n),n)
42     {
43         scanf("%d%d",&a,&b);
44         //count=0;
45         memset(vis,0,sizeof(vis));
46         for(i=1;i<=n;i++)
47         scanf("%d",&map[i]);
48         printf("%d\n",bfs(a,b));
49     }
50 } 

 

posted on 2012-08-05 21:22  仁者无敌8勇者无惧  阅读(164)  评论(0编辑  收藏  举报

导航