UVa 439 Knight Moves 骑士的移动

本文介绍了一种使用广度优先搜索(BFS)算法解决国际象棋中骑士从起点到终点最短移动次数的问题。通过定义骑士可能的移动方向,并采用队列存储待探索的状态,实现了高效的路径查找。

思路:BFS求最短路,遇到终点直接结束

<span style="font-size:14px;">#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
int d[8][2] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
int begin1,begin2,end1,end2;
int chess[8][8];
struct Point{
	int x,y;
	int leng;
};
queue<Point> q;
int bfs()
{
	int kase = 0;
	Point begin,tmp;
	begin.x = begin1;
	begin.y = begin2;
	begin.leng = 0;
	q.push(begin);
	while(!q.empty())
	{
		Point n;
		n = q.front();
		q.pop();
		for(int i = 0;i<8;i++)
		{
		    tmp.x = n.x+d[i][0];
			tmp.y = n.y+d[i][1];
			tmp.leng = n.leng + 1;
			if (tmp.x==end1&&tmp.y==end2)  return n.leng+1;
			else
			{
				if(tmp.x>=0&tmp.x<8&tmp.y>=0&&tmp.y<8)
				{
					q.push(tmp);
				}
			}
		}
	}
}
int main()
{
	char c[5],h[5];
	while(scanf("%s %s", c, h) != EOF)
	{ 
	   memset(chess,0,sizeof(chess));
	   while (!q.empty()) q.pop();
	   begin1 = c[0]-'a';
	   begin2 = c[1]-'1';
	   end1 = h[0] - 'a';
	   end2 = h[1] - '1';
	   int x;
	   if (begin1==end1&&begin2==end2) x = 0;
	   else x = bfs();
	   printf("To get from %s to %s takes %d knight moves.\n",c,h,x);
	}
	return 0;
}</span>


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值