ELEVTRBL - Elevator Trouble - SPOJ Solution C++

  Problem Link : ELEVTRBL 


👉 Hint : Count number of levels using BFS

 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int x,f,s,g,u,d;
    cin>>f>>s>>g>>u>>d;
    if(s==g)
    {
        cout<<"0";
        exit(0);
    }
    int visited[f+1],level[f+1];
    memset(visited,0,sizeof(visited));
    memset(level,0,sizeof(level));
    queue<int>q;
    q.push(s);
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        visited[x]=1;
        if(x==g)
            break;
        if(x<g)
        {
            if(x+u<=f && !visited[x+u])
            {
                level[x+u]=level[x]+1;
                q.push(x+u);
            }
            else if(x-d>=1 && !visited[x-d])
            {
            level[x-d]=level[x]+1;
            q.push(x-d);
            }
        }   
        else 
        
            if(x-d>=1 && !visited[x-d])
            {
            level[x-d]=level[x]+1;
            q.push(x-d);
            }
            else if(x+u<=f && !visited[x+u])
            {
                level[x+u]=level[x]+1;
                q.push(x+u);
            }
    }
    if(level[g]!=0)
        cout<<level[g]<<endl;
    else
        cout<<"use the stairs";
} 

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!