-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathJumpingNumbers.cpp
53 lines (41 loc) · 1.03 KB
/
JumpingNumbers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Print all the jumping numbers smaller than or equal to x
For eg:
x = 15
Output: 0 1 2 3 4 5 6 7 8 9 10 12
Note: A number is called as a jumping number if all adjacent digits in it differ by 1. The difference between '9' and '0'
is not considered as 1.
*/
#include<iostream>
#include<queue>
using namespace std;
void bfs(int x, int num)
{
queue<int> q;
q.push(num);
while (!q.empty()) {
num = q.front();
q.pop();
if (num <= x) {
cout << num << " ";
int last_dig = num % 10;
if (last_dig == 0)
q.push((num * 10) + (last_dig + 1));
else if (last_dig == 9)
q.push((num * 10) + (last_dig - 1));
else {
q.push((num * 10) + (last_dig - 1));
q.push((num * 10) + (last_dig + 1));
}
}
}
}
int main()
{
int x;
cin>>x;
cout << 0 << " ";
for (int i = 1; i <= 9 && i <= x; i++)
bfs(x, i);
return 0;
}