拿来训练一下自己的BFS,注意棋子移动的方向.
题目中的棋子是 马
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct knight
{
int x,y;
int step;
}knight;
typedef struct node
{
int front,rear;
knight place[10000];
}node;
int dir[8][2]={-1,-2,-2,-1,-2,1,-1,2,1,-2,2,-1,2,1,1,2};
node s;
int square[8][8];
knight begin,end;
void init()
{
s.front = s.rear = 0;
}
void enqueue(int x,int y,int foot)
{
s.place[s.rear].x=x;
s.place[s.rear].y=y;
s.place[s.rear].step=foot;
s.rear++;
}
void dequeue()
{
s.front++;
}
int isempty()
{
return s.front==s.rear?1:0;
}
int bfs()
{
int i;
knight tmp,move;
init();
s.place[0].x=begin.x;
s.place[0].y=begin.y;
s.place[0].step=0;
enqueue(begin.x,begin.y,0);
while(!isempty())
{
tmp = s.place[s.front];
dequeue();
if(tmp.x==end.x && tmp.y == end.y)
{
return tmp.step;
}
for(i=0;i<8;i++)
{
move.x=tmp.x+dir[i][0];
move.y=tmp.y+dir[i][1];
if(move.x>=0&&move.x<=7&&move.y>=0&&move.y<=7&&!square[move.x][move.y])
{
move.step=tmp.step+1;
square[move.x][move.y]=1;
enqueue(move.x,move.y,move.step);
}
}
}
return -1;
}
int main()
{
char pos1[3],pos2[3];
int result;
while(scanf("%s%s",pos1,pos2)!=EOF)
{
memset(square,0,sizeof(square));
begin.x=pos1[0]-'a';begin.y=pos1[1]-'1';
end.x=pos2[0]-'a';end.y=pos2[1]-'1';
square[begin.x][begin.y]=1;
result = bfs();
printf("To get from %s to %s takes %d knight moves.\n",pos1,pos2,result);
}
return 0;
}