当前位置: 首页 > news >正文

马的移动(BFS)

题目描述

光头强正在研究国际象棋中的马的问题。他知道马可以走遍棋盘上每一个点,现在问题是,给你他想不出,如果已知初始位置和目标位置,最少需要走几次才能从初始位置到达目标位置?

要不你写个程序帮帮他?

image

输入格式

输入将包含多个测试用例。每个测试用例占一行,两个长度为 22 的字符串代表起点和终点。棋盘的网格横向编号a−ha−h,纵向编号1−81−8。

输出格式

对于每个测试用例,输出一行:

To get from xx to yy takes n knight moves.

样例

输入数据 1

e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

 

输出数据 1

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.

代码实现

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iomanip>
#include <set>
#include <list>
#include <string.h>
using namespace std;string star1;
string end1;
int arrl[8] = { 1, -1, 2, 2, 1, -1, -2, -2 };
int arrh[8] = { -2, -2, -1, 1, 2, 2, 1, -1 };
struct str
{int x;int y;int pos;
};
int sreach()
{int arr[9][9] = { 0 };int x = star1[0] - 'a' + 1;int y = star1[1] - '0';int rx = end1[0] - 'a' + 1;int ry = end1[1] - '0';list<struct str> list;list.push_back({ x,y,0 });arr[x][y] = 1;while (!list.empty()){int xx = list.front().x;int yy = list.front().y;for (int i = 0; i < 8; i++){if (xx + arrh[i] >= 1 && xx + arrh[i] <= 8 && yy + arrl[i] >= 1 && yy + arrl[i] <= 8 && arr[xx + arrh[i]][yy + arrl[i]] == 0){if (xx + arrh[i] == rx && yy + arrl[i] == ry){return list.front().pos + 1;}arr[xx + arrh[i]][yy + arrl[i]] = 1;list.push_back({ xx + arrh[i],yy + arrl[i],list.front().pos + 1 });       }}list.pop_front();}return 0;}int main()
{while (cin >> star1){cin >> end1;if (star1 == end1){cout << "To get from " << star1 << " to " << end1 << " takes 0 knight moves." << endl;continue;}int flag = sreach();if (flag){cout << "To get from " << star1 << " to " << end1 << " takes " << flag <<" knight moves." << endl;}}return 0;
}

相关文章:

  • Causal Attention的底层原理
  • JVM详解(曼波脑图版)
  • Qt GUI 库总结
  • webview真正实现通信!!!
  • Vue 3中处理搜索框输入与数据库请求的交互
  • R4打卡——pytorch实现LSTM预测火灾
  • html+js+clickhouse环境搭建
  • [图像掩膜,ROI切割] 图像预处理(OpenCV)-part4
  • Flask(3): 在Linux系统上部署项目
  • 基于flask+vue框架的灯饰安装维修系统u49cf(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • MAMBA start!!!
  • TTY驱动程序框架
  • QML SpinBox:控件的用法与样式外观
  • vue3中defineEmits的使用说明
  • C++中const的不同使用方法和意义
  • 初识Redis · 命令、数据结构补充、协议
  • 订阅应用 TikTok 广告实用指南
  • 电子电器架构 --- 下一代汽车电子/电气(E/E)架构
  • 长亭2月公开赛Web-ssrfme
  • 智能体数据分析
  • 黄晨光任中科院空间应用工程与技术中心党委书记、副主任
  • 对话|蓬皮杜策展人布莱昂:抽象风景中的中国审美
  • 中国德国商会报告:76%在华德企受美国关税影响,但对华投资战略依然稳固
  • 【社论】三个“靠谱”为市场注入确定性
  • 外交部回应西班牙未来外交战略:愿与之一道继续深化开放合作
  • 科技日报刊文批院士专家“赶场式”跑会:助长浮躁之气功利之心