代码:
#include <iostream>
using namespace std;
int n, m;
int head = 0, tail = 0;
int bfs(int x);
const int N = 100010;
class John
{
public:
int loc;
int time;
};
John s[N];
int used[N];
int main()
{
cin >> n >> m;
cout << bfs(n);
system("pause");
return 0;
}
int bfs(int x)
{
used[x] = 1;
s[head].loc = x; // s[head]={x,0} ,如果是这样写在POJ上会报错
s[head].time = 0;
John J, nJ;
int i, j, k;
while (head <= tail)
{
J = s[head++];
for (i = 0; i < 3; i++) //像迷宫一样使用数组来改变方向,就只能条件判断了(因为有扩大二倍)
{
nJ = J;
if (i == 0)
{
nJ.loc -= 1;
}
else if (i == 1)
{
nJ.loc += 1;
}
else
{
nJ.loc *= 2;
}
if (nJ.loc < 0 || nJ.loc > 100000 || used[nJ.loc])
continue;
else
{
nJ.time++;
used[nJ.loc] = 1;
s[++tail] = nJ;
if (nJ.loc == m)
return nJ.time;
}
}
}
return 0;
}
好久都没有接触广搜的代码了,写起来十分生疏~