先研究下国际象棋中马是怎么走的,然后bfs就哦了。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int map[10][10];
typedef struct Point {
int x;
int y;
int dis;
} Point;
typedef Point* Ptr;
Point queue[5000];
int dir[8][2] = { { -2, 1 }, { -2, -1 }, { -1, 2 }, { 1, 2 }, { -1, -2 }, { 1,
-2 }, { 2, 1 }, { 2, -1 } };
int bfs(Point from, Point to) {
if (from.x == to.x && from.y == to.y)
return 0;
int front = 0;
int rear = 1;
queue[0].x = from.x;
queue[0].y = from.y;
queue[0].dis = from.dis;
while (front < rear) {
Ptr p = &queue[front++];
map[p->x][p->y] = 1;
if (p->x == to.x && p->y == to.y)
return p->dis;
int k;
int newX, newY;
for (k = 0; k < 8; k++) {
newX = p->x + dir[k][0];
newY = p->y + dir[k][1];
if (newX >= 1 && newX <= 8 && newY >= 1 && newY <= 8
&& !map[newX][newY]) {
queue[rear].x = newX;
queue[rear].y = newY;
queue[rear].dis = p->dis + 1;
rear++;
}
}
}
return -1;
}
int main() {
char start[5];
char end[5];
while (scanf("%s%s", start, end) != EOF) {
memset(map, 0, sizeof(map));
Point from, to;
from.x = start[0] - 'a' + 1;
from.y = start[1] - '0';
from.dis = 0;
to.x = end[0] - 'a' + 1;
to.y = end[1] - '0';
to.dis = -1;
printf("To get from %s to %s takes %d knight moves.\n", start, end,
bfs(from, to));
}
return 0;
}