刚开始理解题意,感觉这道题很难懂,不知道棋子怎么走,查了百度骑士的走法后发现自己吃了文化的亏哈哈
一个骑士按照中国象棋中马的走法,只能在1-8和a-h直接走 严格控制不能在0上走
理解题意后 发现这就是道普通的走迷宫 用bfs解决
(说实话这道题的输入输出有点恶心,我的做法仅作参考)
好了 上代码
#include<iostream>
#include<queue>
#include<cstring>
#include<string.h>
#include<string>
#include<map>
using namespace std;
const int N = 10;
int d[N][N];
char zimu[N];
int shuzi[N];
int dx[8] = { -1,-2,-2,-1,1,2,2,1 };//对应8的种走法
int dy[8] = { -2,-1,1,2,2,1,-1,-2 };
char s[100];
//string s1, s2;
char s1[2][2];
char s2[2][2];
struct Pair
{
int x, y;
};
void bfs()
{
map<char, int>mp;
mp['a'] = 1;
mp['b'] = 2;
mp['c'] = 3;
mp['d'] = 4;
mp['e'] = 5;
mp['f'] = 6;
mp['g'] = 7;
mp['h'] = 8;
int k = 0, j = 0;
memset(zimu, 0, sizeof(zimu));
memset(shuzi, 0, sizeof(shuzi));
for (int i = 0; i < strlen(s); i++)
{
if (s[i] <= 'h'&&s[i] >= 'a')
{
zimu[k++] = s[i];
}
else if (s[i] <= '8'&&s[i] >= '1')
{
shuzi[j++] = s[i] - '0';
}
}
//用二位数组记录输入
s1[0][0] = zimu[0]; s1[0][1] = shuzi[0] + '0';
//cout << s1[0] << endl;
s2[0][0] = zimu[1]; s2[0][1] = shuzi[1] + '0';
//cout << s2[0] << endl;
Pair start, end;
start.x = mp[zimu[0]];
start.y = shuzi[0];
end.x = mp[zimu[1]];
end.y = shuzi[1];
if (start.x == end.x&&start.y == end.y)
printf("To get from %s to %s takes %d knight moves.\n", s1[0], s2[0], 0);
for (int i=0; i <= 8; i++)
for (int j = 0; j <= 8; j++)
{
d[i][j] = -1;
}
queue<Pair>q;
while (!q.empty())
{
q.pop();
}
d[start.x][start.y] = 0;
q.push(start);
while (!q.empty())
{
Pair head = q.front();
q.pop();
for (int i = 0; i < 8; i++)
{
Pair next;
//int dx[8] = { -1,-2,-2,-1,1,2,2,1 };
//int dy[8] = { -2,-1,1,2,2,1,-1,-2 };
next.x = head.x + dx[i];
next.y = head.y + dy[i];
if (d[next.x][next.y] == -1 && next.x <= 8 && next.x >= 1 && next.y <= 8 && next.y >=1)
{
d[next.x][next.y] = d[head.x][head.y] + 1;
q.push(next);
if (next.x == end.x&&next.y == end.y)
{
//return d[next.x][next.y];
printf("To get from %s to %s takes %d knight moves.\n",s1[0],s2[0], d[next.x][next.y]);
return;
}
}
}
}
}
int main()
{
//string s;
while (gets_s(s))
{
//printf("To get from e2 to e4 takes %d knight moves.\n", bfs());
//cout << bfs() << endl;
bfs();
memset(s, 0, sizeof(s));
}
}
/*
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
*/