骑士的移动 Knight Moves(洛谷)

题意翻译
输入 8 × 8 的国际象棋棋盘上的 2 个格子(列:a ~ h,行:1 ~ 8),

求马至少多少步从起点(键盘输入的第一个位置)跳到终点(键盘输入的第二个位置)。

输入样例
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

输出样例
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.


题解
BFS:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>

#define x first
#define y second
using namespace std;

const int N = 10;

typedef pair<int, int> PII;

int dist[N][N];
char a, b, c, d;
int x1, y1, x2, y2;

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

int bfs()
{
	queue<PII> q;
	q.push(make_pair(x1, y1));
	dist[x1][y1] = 0;
	
	while(q.size())
	{
		PII t = q.front();
		q.pop();
		
		if(t.x == x2 && t.y == y2) return dist[x2][y2];
		
		for (int i = 0; i < 8; i ++)
		{
			int a = t.x + dx[i], b = t.y + dy[i];
			if(a < 1 || a > 8 || b < 1 || b > 8) continue;
			if(dist[a][b] != -1) continue;
			
			q.push(make_pair(a, b));
			dist[a][b] = dist[t.x][t.y] + 1;			
		}
	}
}

int main()
{
	while(cin >> a >> b >> c >> d)
	{
		memset(dist, -1, sizeof dist);
		x1 = b - '0', y1 = a - 96, x2 = d - '0', y2 = c - 96;
		printf("To get from %c%c to %c%c takes %d knight moves.\n", a, b, c, d, bfs());
	}
	
	return 0;		
}

ps:这道题在洛谷提交有点麻烦,但是有一道类似的 【Knight Moves】

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值