HDU 1372(Knight Moves)

国际象棋中,骑士在一个 3*2 的格子中进行对角线移动,即可以朝八个方向移动,依次进行广搜即可。

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

int dx[8] = { -2,-2,-1,-1,1,1,2,2 };
int dy[8] = { 1,-1,2,-2,2,-2,1,-1 };
bool vis[25][25];

struct node //棋盘上的格子
{
	int x, y; //坐标
	int step; //移动步数
};

//广搜,搜索从(sx,sy)到(ex,ey)的最小步数
int BFS(int sx, int sy, int ex, int ey)
{
	node start;
	start.x = sx; start.y = sy; start.step = 0;
	queue<node> q;
	q.push(start);
	node now, next;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		if (now.x == ex && now.y == ey) //到达终点
			return now.step;
		for (int i = 0; i < 8; i++) //依次搜索8个位置
		{
			next.x = now.x + dx[i];
			next.y = now.y + dy[i];
			next.step = now.step + 1;
			if (!vis[next.x][next.y] && next.x > 0 && next.y > 0 && next.x <= 8 && next.y <= 8)
			{
				vis[next.x][next.y] = 1;
				q.push(next);
			}
		}
	}
}

int main()
{
	char s1[2], s2[2];
	while (cin >> s1 >> s2)
	{
		memset(vis, 0, sizeof(vis));
		int x1 = s1[0] - 'a' + 1;
		int y1 = s1[1] - '0';
		int x2 = s2[0] - 'a' + 1;
		int y2 = s2[1] - '0';
		cout << "To get from " << s1 << " to " << s2 << " takes " << BFS(x1, y1, x2, y2) << " knight moves." << endl;
	}
}

继续加油。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值