Stepping Numbers | A Java program to find all the Stepping Numbers in range [ n , m ] using DFS Approach ; Method display 's all the stepping numbers  in range [n, m] ; If Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m then return ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using DFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]
import java . util . * ; class Main { public static void dfs ( int n , int m , int stepNum ) { if ( stepNum <= m && stepNum >= n ) System . out . print ( stepNum + " ▁ " ) ; if ( stepNum == 0 stepNum > m ) return ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) dfs ( n , m , stepNumB ) ; else if ( lastDigit == 9 ) dfs ( n , m , stepNumA ) ; else { dfs ( n , m , stepNumA ) ; dfs ( n , m , stepNumB ) ; } } public static void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) dfs ( n , m , i ) ; } public static void main ( String args [ ] ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }