一条线上的搜索
行动有三种情况,就计做三种走的方式 +1, -1, *2
struct node{
int pos,step;
};
struct node head;
queue <struct node> q;
int N,K;//起始位置和终止位置
int vis[len];
int main(){
while (cin >> N >> K) {
Init();
bfs();
}
return 0;
}
void Init(){
memset(vis, 0, sizeof(vis));
while (!q.empty()) q.pop();
struct node tmp;
vis[N] = 1;
tmp.pos = N; tmp.step = 0;
q.push(tmp);
}
void bfs(){
while (!q.empty()) {
head = q.front();
q.pop();
if(head.pos == K){cout << "0" << endl; continue;}
//有可能不用跑 。这里有个坑
for (int i=0; i<3; i++) {
switch (i) {
case 0:{
int _x = head.pos + 1;
if (_x == K) {cout << head.step + 1 << endl;return;}
if (_x >= len) continue;
if (vis[_x] == 1) continue;
struct node tmp;
tmp.pos = _x; tmp.step = head.step + 1;
q.push(tmp);
vis[_x] ++;
break;
}
case 1:{
int _x = head.pos - 1;
if (_x == K) {cout << head.step + 1 << endl;return;}
if (_x < 0) continue;
if (vis[_x] == 1) continue;
struct node tmp;
tmp.pos = _x; tmp.step = head.step + 1;
q.push(tmp);
vis[_x] ++;
break;
}
case 2:{
int _x = head.pos * 2;
if (_x == K) {cout << head.step + 1 << endl;return;}
if (_x >= len) continue;
if (vis[_x] == 1) continue;
struct node tmp;
tmp.pos = _x; tmp.step = head.step + 1;
q.push(tmp);
vis[_x] ++;
break;
}
}
}
}
}