首页 > 其他 > 详细

P1135 奇怪的电梯

时间:2021-04-07 20:46:41      阅读:30      评论:0      收藏:0      [点我收藏+]

 

吐槽

第一道同时用BFS和DFS两种方法做出来的题目

题目

技术分享图片

 

 

BFS

最大的注意点就是判断是否经历过该楼层

#include<bits/stdc++.h>
using namespace std;
int n,a,b;
int dis[201],f[201];
queue<int> q;
bool check(int x){
    return x>=1&&x<=n;
}
void bfs()
{
    int t;
    while(!q.empty()){
        int p=q.front();
        q.pop();
        if(p==b){
            cout<<dis[b];
            return;
        }
        t=p+f[p];
        if(check(t)&&dis[t]==0){//注意进行判断是否已经经历过这个楼层
            dis[t]=dis[p]+1;
            q.push(t);
        }
        t=p-f[p];
        if(check(t)&&dis[t]==0){
            dis[t]=dis[p]+1;
            q.push(t);
        }
    }
    cout<<-1;
}

int main()
{
    cin>>n>>a>>b;
    for (int i = 1; i <= n; i++){
        cin>>f[i];
    }
    q.push(a);
    dis[a]=0;
    bfs();
    return 0;
}

DFS

 这道题用DFS好难,做了好久

#include<bits/stdc++.h>
using namespace std;
int n,a,b,ans=INT_MAX;//注意我们求得是最小值,也就是说我们需要遍历所有可能
int to[201];
bool vis[201];
bool check(int x,int sum)
{
    return !vis[x]&&x>=1&&x<=n&&sum<ans;
}
void dfs(int now,int sum)
{
    if(now==b){
        ans=min(sum,ans);
        return;
    }
    vis[now]=1;//遍历过赋值为1
    int t=now+to[now];
    if(check(t,sum)){
        dfs(t,sum+1);
    }
    t=now-to[now];
    if(check(t,sum)){
        dfs(t,sum+1);
    }
    vis[now]=0;//回溯,当该序列中由于下面的序列符合条件,一定要记得将其置为未遍历状态
}
int main()
{
    cin>>n>>a>>b;
    for(int i=1;i<=n;i++){
        cin>>to[i];
    }
    vis[a]=1;
    dfs(a,0);
    if(ans!=INT_MAX){
        cout<<ans;
    }
    else{
        cout<<-1;
    }
    return 0;
}

 

P1135 奇怪的电梯

原文:https://www.cnblogs.com/lvjt0208/p/14628894.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!