|
题目描述:
要求选给出思路,然后写代码,可以使用c/c++/java/python或者伪代码描述。
有两个数,A和B,六种操作分别是+12,-12,+7,-7,+5,-5。A经过若干次操作,变成B
是输入任意2个数A和B,要给出变换过程,这其中的操作序列就是一个路径,也就是最少的操作次数 。
思路:
用广度优先搜索穷举,找出最短路径
#include <iostream>
#include <queue>
using namespace std;
class node
{
public:
int x,dx;
struct node *prev;
node(int y,int dy,struct node *p):x(y),dx(dy),prev(p){}
};
int main()
{
queue<node *> Q;
int a, b, i, d[] = {12,-12,7,-7,5,-5};
cin >> a >> b;
node *t;
Q.push(new node(a,0,NULL));
while(!Q.empty())
{
t = Q.front();
if(t->x == b)break;
Q.pop();
for(i=0; i<6; i++)
Q.push(new node(t->x+d[i],d[i],t));
}
while(t->prev)
{
cout << t->dx << endl;
t = t->prev;
}
return 0;
}
|