Numbers with one absolute difference - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Monday, 3 August 2020

Numbers with one absolute difference


Numbers with one absolute difference

Numbers with one absolute difference


Given a number N. The task is to print all the numbers less than or equal to N in increasing order, with the fact that absolute difference between any adjacent digits of number should be 1.


#include <bits/stdc++.h>
using namespace std;
void find(queue<long long int> &q,long long int n)
{
    while(!q.empty())
    {
        long long int p=q.front();
        q.pop();
       
        if(p>9&&p<=n)
        {
            cout<<p<<" ";
        }
       
        long long int i=p%10;
       
        if(i!=0)
        {
            long long int j=10*p+(i-1);
            if(j<=n)
            q.push(j);
        }
       
        if(i!=9)
        {
            long long int k=10*p+(i+1);
            if(k<=n)
            q.push(k);
        }
       
    }
}
int main() {
    //code
    int t;
    cin>>t;
    while(t--)
    {
        long long int n;
        cin>>n;
        if(n<10)
        {
        cout<<-1<<" ";
        }else{
            queue<long long int> q;
            for(int i=1;i<10;++i)
            q.push(i);
           
            find(q,n);
        }
       
         cout<<endl;
        
    }
    return 0;
}