马的移动(BFS)
题目描述
光头强正在研究国际象棋中的马的问题。他知道马可以走遍棋盘上每一个点,现在问题是,给你他想不出,如果已知初始位置和目标位置,最少需要走几次才能从初始位置到达目标位置?
要不你写个程序帮帮他?
输入格式
输入将包含多个测试用例。每个测试用例占一行,两个长度为 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;
}