UVA439 Knight Moves
题目大意
有一个骑士,他可以骑马日字型跳跃,问他从A点到B点最少要几步
解题思路
这题就是一个特别裸的广搜板子
它的主要问题在于输入输出
输入的数据我们可以用
然后我们为了方便处理,把行也映射成数组1 ~ 8
所以有了我们的读入代码
预编译指令
#define x first
#define y second
定义的
pair<char, int> A, B;
while (cin >> A.x >> A.y >> B.x >> B.y)
{
int sx = A.x - 'a' + 1, sy = A.y,
fx = B.x - 'a' + 1, fy = B.y;
//printf这句是输出
然后就是巨坑无比的输出了
一定要有句号!!!!!!!!!
代码
#include <iostream>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
struct Point
{
int x, y, dist;
Point(int a = 0, int b = 0, int c = 0) : x(a), y(b), dist(c) {}
} ;
pair<char, int> A, B;
int mp[9][9];
int bfs(int& sx, int& sy, int& fx, int& fy)
{
if (sx == fx && sy == fy) return 0;
queue<Point> q;
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
q.push(Point(sx, sy, 0));
while (q.size())
{
Point t = q.front(); q.pop();
for (int i = 0; i < 8; i ++ )
{
int x = t.x + dx[i], y = t.y + dy[i];
if (x < 1 || x > 8 || y < 1 || y > 8) continue ;
if (mp[x][y]) continue ;
Point now = Point(x, y, t.dist + 1);
if (now.x == fx && now.y == fy) return now.dist;
q.push(now);
}
}
}
int main()
{
while (cin >> A.x >> A.y >> B.x >> B.y)
{
int sx = A.x - 'a' + 1, sy = A.y,
fx = B.x - 'a' + 1, fy = B.y;
printf("To get from %c%d to %c%d takes %d knight moves.\n",
A.x, A.y, B.x, B.y, bfs(sx, sy, fx, fy));
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)