UVA 439-Knight Moves
题目大意:给出国际象棋棋盘俩个坐标,求马从坐标1到坐标2的最短步数
解题思路:bfs寻找最短路
#include <stdio.h>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
struct kni{
int x, y, d;
};
int dir[8][2] = {{1, 2}, {-1, 2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, -2}, {-1, -2}};
queue<kni> que;
int map[9][9];
int bfs(int a, int b) {
while(!que.empty()) {
if(que.front().x == a && que.front().y == b)
return 0;
for(int i = 0; i < 8; i++) {
int c = que.front().x + dir[i][0], d = que.front().y + dir[i][1];
if(c > 0 && c <= 8 && d > 0 && d <= 8 && map[c][d] == 0) {
if(c == a && d == b)
return que.front().d + 1;
else {
map[que.front().x][que.front().y] = 1;
kni kk;
kk.x = c;
kk.y = d;
kk.d = que.front().d+1;
que.push(kk);
}
}
}
que.pop();
}
return -1;
}
int main() {
char ch1, ch2;
int x1, x2, y1, y2;
while(cin >> ch1 >> y1 >> ch2 >> y2) {
while(!que.empty())
que.pop();
memset(map, 0, sizeof(map));
x1 = ch1 - 'a' + 1;
x2 = ch2 - 'a' + 1;
kni k;
k.x = x1;
k.y = y1;
k.d = 0;
que.push(k);
int re = bfs(x2, y2);
printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, y1, ch2, y2, re);
}
return 0;
}