439 - Knight Moves

/*
马走棋盘问题
解题思路:
广度优先搜索
使用二维数组step来记录步数
*/

#include <cstdio>
#include <cstring>

bool chessboard[10][10];
int step[10][10];
int dir[8][2]={1,2,2,1,1,-2,2,-1,-1,2,-2,1,-1,-2,-2,-1};
bool over;
struct Node
{
	int x,y;
	Node(){}
	Node(int x,int y):x(x),y(y){}
};
struct Queue
{
	int rear,front;
	Node data[70];
	Queue()
	{
		rear=front=0;
		memset(data,0,sizeof(data));
	}
};
bool check(int x,int y)
{
	if(x>=1 && x<=8 && y>=1 && y<=8)
		return true;
	return false;
}

void bfs(int sx,int sy,int ex,int ey)
{
	Queue q;
	q.data[q.rear++]=Node(sx,sy);
	while(q.front!=q.rear)
	{
		Node a;
		a=q.data[q.front++];
		int x,y;
		for(int i=0;i<8;i++)
		{
			x=a.x+dir[i][0];
			y=a.y+dir[i][1];
			if(check(x,y) && chessboard[x][y]==0)
			{
				chessboard[x][y]=1;
				step[x][y]=step[a.x][a.y]+1;
				q.data[q.rear++]=Node(x,y);
			}
			if(x==ex && y==ey)
				break;
		}
	}
}

int main()
{
	//freopen("data.in","r",stdin);
	int c1,r1,c2,r2;
	char a1,a2;
	while(scanf("%c%d %c%d\n",&a1,&r1,&a2,&r2)!=EOF)
	{
		//getchar();
		c1=a1-'a'+1;
		c2=a2-'a'+1;
		memset(chessboard,0,sizeof(chessboard));
		memset(step,0,sizeof(step));
		over=false;
		if(r1!=r2 || c1!=c2)
		{
			chessboard[r1][c1]=1;
			bfs(r1,c1,r2,c2);
		}
		printf("To get from %c%d to %c%d takes %d knight moves.\n",a1,r1,a2,r2,step[r2][c2]);
	}
	return 0;
}


你可能感兴趣的:(c,struct)