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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值