题目大意:国际象棋,棋盘为8*8的大小,骑士走法为日字走法,如中国象棋的马。问从一个点到另一个点,最少走几步。

解题思路:骑士走的方向有八个,两个方向数组,标记数组也做为步数数组,类似迷宫问题。不详细说了。

ac代码:

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
char c1, c2;
queue <int> qu;
int n, m, p, q, vis[10][10];
int dx[8] = {-2, -2, 2, 2, -1, 1, -1, 1};
int dy[8] = {-1, 1, -1, 1, -2, -2, 2, 2};
int bfs()
{
int temp1, temp2, x, y;
while (!qu.empty())
qu.pop();
for (int i=0; i<10; i++)
memset(vis[i], -1, sizeof(vis[i]));
vis[p][n] = 0;
qu.push(p), qu.push(n);
while (!qu.empty()){
temp1 = qu.front();
qu.pop();
temp2 = qu.front();
qu.pop();
if (temp1 == q && temp2 == m)
return vis[q][m];
for (int i=0; i<8; i++){
x = temp1 + dx[i];
y = temp2 + dy[i];
if (x >=0 && x < 8 && y >= 0
&& y < 8 && vis[x][y] == -1){
qu.push(x), qu.push(y);
vis[x][y] = vis[temp1][temp2] + 1;
}
}
}
}
int main()
{
while (scanf("%c%d %c%d", &c1, &n, &c2, &m)!=EOF){
p = c1 - 'a', q = c2 - 'a';
n--, m--;
printf("To get from %c%d to %c%d", c1, n+1, c2, m+1);
printf(" takes %d knight moves.\n", bfs());
getchar();
}
return 0;
}