#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <algorithm>
using namespace std;
int xx[ ] = {1,2,-1,-2,-2,-1,1,2};
int yy[ ] = {2,1,-2,-1,1,2,-2,-1};
int map[10][10];
int a, b, c, d, f1 = 0;
int judge( int x, int y)
{
if ( x < 1 || x > 8 || y < 1 || y > 8)
return 0;
return 1;
}
struct node
{
int x, y, t;
}NODE;
void BFS( )
{
int i, j, x1, x2, y1, y2, t;
queue<node>q;
NODE.x = a, NODE.y = b, NODE.t = 0;
q.push(NODE);
while ( !q.empty( ))
{
NODE = q.front( );
q.pop( );
x1 = NODE.x, y1 = NODE.y, t = NODE.t;
if (x1 == c && y1 == d)
{
f1 = t;
break;
}
for (i = 0; i < 8; i++)
{
x2 = x1 + xx[i];
y2 = y1 + yy[i];
if (judge(x2,y2))
{
NODE.x = x2, NODE.y = y2, NODE.t = t + 1;
q.push(NODE);
}
}
}
}
int main( )
{
char ch1[10], ch2[10];
while (scanf("%s%s",ch1, ch2) != EOF)
{
f1 = 0;
a = ch1[0] - 'a' + 1;
b = ch1[1] - '0';
c = ch2[0] - 'a' + 1;
d = ch2[1] - '0';
BFS( );
printf("To get from %s to %s takes %d knight moves.\n",ch1, ch2, f1);
}
return 0;
}
转载于:https://www.cnblogs.com/tangcong/archive/2011/08/09/2132574.html