一个8行8列的棋谱,任意给出knight的两个位子,问按照knight的走法,从其中的一个位子出发,问至少需要经过几步到达另外一个位子。 行用1-8表示,列用a-h表示,起始位置入队列,然后在当前结点能访问的结点依次搜索。。在进入队列前判断是否到达结束位置,用二维数组存储步数、、、、点击打开链接
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
typedef struct {
int x;
int y;
}point;
vector<point> v;
int step[8][8];
point p;
bool ok; //不知道为什么就是不让用find
int index;
int start_x, start_y, end_x, end_y;
int bfs(int x, int y, int time) // time 每次记录当前的步数
{
if(x==end_x && y==end_y)
{
ok = true;
return 0;
}
if(x-2>=0&&y-1>=0&&step[x-2][y-1]==-1) //依次搜索
{
step[x-2][y-1] = time+1;
p.x = x-2;
p.y = y-1;
v.push_back(p);
}
if(x-1>=0&&y-2>=0&&step[x-1][y-2]==-1)
{
step[x-1][y-2] = time+1;
p.x = x-1;
p.y = y-2;
v.push_back(p);
}
if(x-2>=0&&y+1<8&&step[x-2][y+1]==-1)
{
step[x-2][y+1] = time+1;
p.x = x-2;
p.y = y+1;
v.push_back(p);
}
if(x-1>=0&&y+2<8&&step[x-1][y+2]==-1)
{
step[x-1][y+2] = time+1;
p.x = x-1;
p.y = y+2;
v.push_back(p);
}
if(x+1<8&&y+2<8&&step[x+1][y+2]==-1)
{
step[x+1][y+2] = time+1;
p.x = x+1;
p.y = y+2;
v.push_back(p);
}
if(x+2<8&&y+1<8&&step[x+2][y+1]==-1)
{
step[x+2][y+1] = time+1;
p.x = x+2;
p.y = y+1;
v.push_back(p);
}
if(x+2<8&&y-1>=0&&step[x+2][y-1]==-1)
{
step[x+2][y-1] = time+1;
p.x = x+2;
p.y = y-1;
v.push_back(p);
}
if(x+1<8&&y-2>=0&&step[x+1][y-2]==-1)
{
step[x+1][y-2] = time+1;
p.x = x+1;
p.y = y-2;
v.push_back(p);
}
}
int main()
{
char s, e;
int _s, _e;
while(cin>>s>>_s>>e>>_e)
{
memset(step, -1, sizeof(step));
start_x = (int)(s-'a');
start_y = _s-1;
end_x = (int)(e-'a');
end_y = _e-1;
p.x = start_x;
p.y = start_y;
v.clear();
step[p.x][p.y]=0;
v.push_back(p);
ok = false;
index = 0;
while(!ok)
{
bfs(v[index].x, v[index].y, step[v[index].x][v[index].y]);
index++;
}
cout<<"To get from "<<s<<_s<<" to "<<e<<_e<<" takes "<<step[end_x][end_y]<<" knight moves."<<endl;
}
system("pause");
return 0;
}