Created
June 12, 2017 17:38
-
-
Save Kaushal28/bd945806a827fdc0d9a7f016a0aaaad9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.LinkedList; | |
class GFG { | |
public static int counter; | |
public static void BFS(int num, int x, int[] a){ | |
LinkedList<Integer> q = new LinkedList<>(); | |
q.add(num); | |
while(q.size()!=0){ | |
int current = q.poll(); | |
if(current <= x){ | |
a[++counter] = current; | |
int last_digit = current%10; | |
if(last_digit == 0){ | |
q.add((current*10) + (last_digit+1)); | |
} else if(last_digit == 9){ | |
q.add((current*10) + (last_digit-1)); | |
} else{ | |
q.add((current*10) + (last_digit-1)); | |
q.add((current*10) + (last_digit+1)); | |
} | |
} | |
} | |
} | |
public static void printAllnumbers(int n, int a[]){ | |
a[0] = 0; | |
for(int i=1;i<=9&&i<=n;i++){ | |
BFS(i, n, a); | |
} | |
for(int i=0;i<=counter;i++){ | |
System.out.print(a[i]+ " "); | |
} | |
System.out.println(); | |
} | |
public static void main (String[] args) { | |
Scanner in = new Scanner(System.in); | |
int t = in.nextInt(); | |
while(t-->0){ | |
counter = 0; | |
int n = in.nextInt(); | |
int a[] = new int[n+1]; | |
printAllnumbers(n, a); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment