题解 | #求x到y的最少计算次数# bfs
求x到y的最少计算次数
https://www.nowcoder.com/practice/45d04d4d047c48768543eeec95798ed6
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int x, y;
stack<int> st;
int s[201];
int main() {
scanf("%d,%d", &x, &y);
if(x == y){
cout << 0 << endl;
return 0;
}
int d = 0;
st.push(x);
s[x + 100] = 1;
//出栈
while (st.size()) {
d ++;
vector<int> tmp;
// printf("d=%d\n",d);
while (st.size()) {
int t = st.top();
// printf("%d ", t);
st.pop();
tmp.push_back(t);
}
// printf("\n");
for (int tt : tmp) {
for (int i = 0; i < 3; i++) {
int a = tt + 1;
if (a == y) {
cout << d << endl;
return 0;
}
if (s[a + 100] == 0) {
st.push(a);
s[a + 100] = 1;
}
a = tt - 1;
if (a == y) {
cout << d << endl;
return 0;
}
if (s[a + 100] == 0) {
st.push(a);
s[a + 100] = 1;
}
a = tt * 2;
if (a == y) {
cout << d << endl;
return 0;
}
if (s[a + 100] == 0) {
st.push(a);
s[a + 100] = 1;
}
}
}
}
return 0;
}
// 64 位输出请用 printf("%lld")
