题目大意:有一个8*8的国际象棋棋盘,输入起点和终点,问马最少走几步。
方法:用一次bfs,难点应该是计算最少步数,解决方法是设置一个层,每次遍历父节点周围的子节点就执行子节点的层=父节点的层+1,这样一来每个节点都有自己的层,每个节点都是公平的所以最后搜索出来直接就是最小步数。
代码:
#include<iostream>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
int direct[16] = { 2,1,1,2,-2,1,-1,2,-2,-1,-1,-2,2,-1,1,-2 };
int mp[10][10]; int vis[10][10]; int lay[10][10];
struct Node {
int x, y;
Node(){}
Node(int _x,int _y):x(_x),y(_y){}
bool operator==(const Node &u) {
return x== u.x&& y == u.y;
}
};
void bfs(int x, int y, int count) {
queue<Node>q;
queue<Node>endqueue;
q.push(Node(x, y)); Node t;
endqueue.push(q.back());
while (!q.empty()) {
t = q.front(); q.pop();
vis[t.x][t.y] = 1;
if (mp[t.x][t.y] == 1) {
printf("To get from %c%d to %c%d takes %d knight moves.\n", x + 'a' - 1, y, t.x + 'a' - 1,t.y,lay[t.x][t.y]);
break;
}
for (int i = 0; i < 16; i += 2) {
int x0 = t.x + direct[i];
int y0 = t.y + direct[i + 1];
if (!vis[x0][y0] && x0 >= 1 && x0 <= 8 && y0 >= 1 && y0 <= 8) {
lay[x0][y0] = lay[t.x][t.y] + 1; q.push(Node(x0, y0));
}
}
}
}int main()
{
string s1,e1;
while (cin >> s1 && cin >> e1) {
memset(mp, 0, sizeof(mp));
memset(vis, 0, sizeof(vis));
memset(lay, 0, sizeof(lay));
mp[e1[0] - 'a' + 1][e1[1] - '0'] = 1;
bfs(s1[0] - 'a' + 1, s1[1] - '0',0);
}
return 0;
}