题意大概就是在国际象棋上,问马从a点到b点需要的最短步数。马的走法和中国象棋的类似。
思路:这种求最少步数或者最小次数的题一般都是用广度搜索来解就行了。
#include <iostream>
using namespace std;
#include <queue>
#include <string.h>
int s1, s2, e1, e2;
int map[8][8];
int x2x[8] = {1, 2, 1, 2, -1, -2, -1, -2}; //把可以走的方向用数组记录下来
int y2y[8] = {2, 1, -2, -1, 2, 1, -2, -1};
int bfs()
{
int x1, y1, x2, y2;
memset(map, 0, sizeof(map));
queue<int>q;
q.push(s1);
q.push(s2);
while(!q.empty())
{
x1 = q.front();
q.pop();
y1 = q.front();
q.pop();
if(x1 == e1 && y1 == e2) //达到终点了就直接return步数
{
return map[x1][y1];
}
for(int i = 0; i < 8; i++)
{
x2 = x1 + x2x[i];
y2 = y1 + y2y[i];
if(x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 || map[x2][y2]>0) //如果走的下一步不在图中直接continue
{
continue;
}
map[x2][y2] = map[x1][y1] + 1; //步数加1
q.push(x2);
q.push(y2);
}
}
return 0;
}
int main()
{
char a[3], b[3];
while(cin>>a>>b)
{
s1 = a[0] - 'a'; //行数
s2 = a[1] - '1'; //列数
e1 = b[0] - 'a'; //行数
e2 = b[1] - '1'; //列数
int total = bfs();
cout<<"To get from "<<a<<" to "<<b<<" takes "<<total<<" knight moves."<<endl;
}
}