-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathStepping_Numbers.cpp
53 lines (46 loc) · 1.17 KB
/
Stepping_Numbers.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
#include<bits/stdc++.h>
using namespace std;
void bfs(int n, int m, int num)
{
// Queue will contain all the stepping Numbers
queue<int> q;
q.push(num);
while (!q.empty())
{
int stepNum = q.front();
q.pop();
if (stepNum <= m && stepNum >= n)
cout << stepNum << " ";
// If Stepping Number is 0 or greater than m,
// no need to explore the neighbors
if (num == 0 || stepNum > m)
continue;
int lastDigit = stepNum % 10;
// There can be 2 cases either digit to be
// appended is lastDigit + 1 or lastDigit - 1
int stepNumA = stepNum * 10 + (lastDigit- 1);
int stepNumB = stepNum * 10 + (lastDigit + 1);
if (lastDigit == 0)
q.push(stepNumB);
else if (lastDigit == 9)
q.push(stepNumA);
else
{
q.push(stepNumA);
q.push(stepNumB);
}
}
}
void displaySteppingNumbers(int n, int m)
{
for (int i = 0 ; i <= 9 ; i++)
bfs(n, m, i);
}
int main()
{
int n , m ;
cout<<"Enter Two numbers:"<<endl;
cin>>n>>m;
displaySteppingNumbers(n,m);
return 0;
}