//这题和1915是一样的题目,只不过这题的输入需要进行转换,还有这题没有给出具体的棋盘和棋子的
//走法,如果对国际象棋不熟悉的人来讲,是很难读得明白题意的,棋盘和棋子的走法可以参照1915题!
#include <iostream>
#include <string>
#include <map>
using namespace std;
const int MAX = 15;
map<char, int> m;
string input1, input2;
int l, r, sx, sy, ex, ey, dir[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
bool vis[MAX][MAX];
//结构体储存一个点的坐标和到达这个点的步数!
struct Info{
int x, y;
int step;
}info[MAX*MAX];
//进行宽搜,得出另一个符合要求的坐标点,储存入数组,然后再一一进行搜索!
void solve(int x, int y)
{
if (x >= 0 && x < 8 && y >= 0 && y < 8 && !vis[x][y]){
info[r].x = x;
info[r].y = y;
info[r].step = info[l].step + 1;
vis[x][y] = 1;
r++;
}
}
void bfs()
{
int i, tmpx, tmpy;
info[0].x = sx;
info[0].y = sy;
vis[sx][sy] = 1;
l = 0;//以一个链表的形式进行搜索结果的储存!
r = 1;
while (l != r){
if (info[l].x == ex && info[l].y == ey){
//printf("To get from %s to %s takes %d knight moves.\n", input1, input2, info[l].step);
cout << "To get from " << input1 << " to " << input2 << " takes " << info[l].step << " knight moves." << endl;
break;
}
//八个方向的坐标转换,再一一进行宽搜!
for (i = 0; i < 8; i++){
tmpx = info[l].x + dir[i][0];
tmpy = info[l].y + dir[i][1];
solve(tmpx, tmpy);
}
l++;
}
return ;
}
int main()
{
m['a'] = 1, m['b'] = 2, m['c'] = 3, m['d'] = 4,
m['e'] = 5, m['f'] = 6, m['g'] = 7, m['h'] = 8;
while (cin >> input1 >> input2){
//对输入进行字符串和数字之间的转换!
sx = m[input1[0]] - 1;
sy = input1[1] - 48 - 1;
ex = m[input2[0]] - 1;
ey = input2[1] - 48 - 1;
memset(vis, 0, sizeof(vis));
bfs();
}
system("pause");
}
poj 2243 Knight Moves
最新推荐文章于 2022-02-25 21:57:21 发布