Find a number in minimum steps | C ++ program to find a number in minimum steps ; To represent data of a node in tree ; Prints level of node n ; Create a queue and insert root ; Do level order traversal ; Remove a node from queue ; To avoid infinite loop ; Check if dequeued number is same as n ; Insert children of dequeued node to queue ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define InF  99999 NEW_LINE struct number { int no ; int level ; public : number ( ) { } number ( int n , int l ) : no ( n ) , level ( l ) { } } ; void findnthnumber ( int n ) { queue < number > q ; struct number r ( 0 , 1 ) ; q . push ( r ) ; while ( ! q . empty ( ) ) { struct number temp = q . front ( ) ; q . pop ( ) ; if ( temp . no >= InF temp . no <= - InF ) break ; if ( temp . no == n ) { cout << " Found ▁ number ▁ n ▁ at ▁ level ▁ " << temp . level - 1 ; break ; } q . push ( number ( temp . no + temp . level , temp . level + 1 ) ) ; q . push ( number ( temp . no - temp . level , temp . level + 1 ) ) ; } } int main ( ) { findnthnumber ( 13 ) ; return 0 ; }