原题见上一篇博文:奇怪的电梯题目以及dfs解法
代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52#include<bits/stdc++.h> using namespace std; int n,A,B,cnt,s; int k[210]; bool b[210]={0};//标记楼层是否已经走过 int d[2]={1,-1};//上楼加,下楼减 struct node{ int d; int step; }a[200000],y,next; //第一次是三个没过 //改完,第二次是2个没过 //继续改遇到瓶颈了 ,反复看了好久才发现问题在哪里, //应该是y=a[front++],但是却写成了y.d=a[front++].d,相当于每次step都没给数值所以才会出错的啊 int bfs(int x,int step) { int front=0,rear=0; a[rear].d=x; a[rear].step=step; rear++; b[x]=false; while(rear!=front){ y=a[front++]; if(y.d==B) return y.step; if(y.d+k[y.d] <=n && b[y.d+k[y.d]]) { b[y.d+k[y.d]]=false; next.d=y.d+k[y.d]; next.step=y.step+1; a[rear++]=next; } if(y.d-k[y.d]>=1 && b[y.d-k[y.d]]) { b[y.d-k[y.d]]=false; next.d=y.d-k[y.d]; next.step=y.step+1; a[rear++]=next; } } return -1; } int main(){ cin>>n>>A>>B; memset(b,true,sizeof(b)); for(int i=1;i<=n;i++) cin>>k[i]; if(A==B) cnt=0;//注意:如果当前楼层和要到达的楼层是一样的cnt=0 else cnt=bfs(A,0); cout<<cnt; return 0; }
最后
以上就是忧郁蜗牛最近收集整理的关于【广度优先搜索BFS】奇怪的电梯的全部内容,更多相关【广度优先搜索BFS】奇怪内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复