520B. Two Buttons - Codeforces Solution C++

  Problem Link : 520B. Two Buttons 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int

unordered_set<int> us;

int bfs(int n, int m)
{
	int cnt=0;
	queue<int> q;
	q.push(n);
	us.insert(n);
	while(!q.empty())
	{
		int s=q.size();
		while(s--)
		{
			int v=q.front();
			if(v==m)
				return cnt;
			q.pop();
			if(v*2<=100000 && us.find(v*2)==us.end())
			{
				us.insert(v*2);
				q.push(v*2);
			}
			if(v-1>0 && us.find(v-1)==us.end())
			{
				us.insert(v-1);
				q.push(v-1);
			}
		}
		cnt++;
	}
}

int main()
{
	int n,m;
	cin>>n>>m;

	cout<<bfs(n,m);

}

 

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!!