码出来了,不过不知道这种写法标准不,回去看看数据结构。
PS:又修改了一下。
看下时间,最长的是深度,不过内存少。然后第一次写的广度,最后是这个广度的版本。
#include <iostream>
#include <cstring>
using namespace std;
int step1[8] = {1,1,2,2,-1,-1,-2,-2};
int step2[8] = {2,-2,1,-1,2,-2,1,-1};
int knight[8][8];
int Queuex[10000],Queuey[10000];
int rear = 0,fron = -1;
void bfsFind(int st1,int st2,int moves)//广度搜索
{
knight[st1][st2] = moves;
while(rear != fron)
{
fron += 1;
for(int m = 0;m < 8;m++)
{
if(st1 + step1[m]< 0 || st1 + step1[m]> 7 || st2 + step2[m]< 0 || st2 + step2[m]> 7 || moves+1 >= knight[st1 + step1[m]][st2 + step2[m]])
continue;
Queuex[rear] = st1 + step1[m];
Queuey[rear] = st2 + step2[m];
rear++;
knight[st1 + step1[m]][st2 + step2[m]] = moves+1;
}
st1 = Queuex[fron];
st2 = Queuey[fron];
moves = knight[Queuex[fron]][Queuey[fron]];
}
}
int main()
{
string a,b;
while(cin >> a >> b)
{
rear = 0,fron = -1;
memset(knight,100,sizeof(knight));
bfsFind(a[0]-'a',a[1]-'1',0);
cout << "To get from "<< a << " to " << b << " takes " << knight[b[0] - 'a'][b[1] - '1'] << " knight moves." << endl;
}
return 0;
}