//uva 439 - Knight Moves
//题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=105&page=show_problem&problem=380
//题目大意就是给出起点和终点,走日字,问最少多少次能到达
//这题以前在hdu的diy上做过一次,这次一次A了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct Node{
int x, y;
}begin_node, end_node;
queue<Node> node_que;
int direction[8][2] = {{1, 2}, {2, 1}, {-1, 2}, {2, -1}, {-1, -2}, {-2, 1}, {-2, -1}, {1, -2}};
int map[10][10];
int num1, num2;
char ch1, ch2, buf;
bool Inmap(Node);
void BFS();
int main(){
while(scanf("%c%d%c%c%d%c", &ch1, &num1, &buf, &ch2, &num2, &buf) != EOF){
memset(map, -1, sizeof(map));
begin_node.x = ch1 - 'a';
begin_node.y = num1 - 1;
end_node.x = ch2 - 'a';
end_node.y = num2 - 1;
BFS();
printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, num1, ch2, num2, map[end_node.x][end_node.y]);
}
return 0;
}
void BFS(){
Node tmp_node;
node_que.push(begin_node);
map[begin_node.x][begin_node.y] = 0;
while(node_que.size()){
begin_node = node_que.front();
node_que.pop();
if(begin_node.x == end_node.x && begin_node.y == end_node.y)
break;
for(int i = 0; i < 8; i++){
tmp_node.x = begin_node.x + direction[i][0];
tmp_node.y = begin_node.y + direction[i][1];
if(Inmap(tmp_node) && map[tmp_node.x][tmp_node.y] == -1){
map[tmp_node.x][tmp_node.y] = map[begin_node.x][begin_node.y] + 1;
node_que.push(tmp_node);
}
}
}
while(node_que.size()){
node_que.pop();
}
}
bool Inmap(Node node){
return node.x >= 0 && node.y >= 0 && node.x < 8 && node.y < 8;
}
uva 439 - Knight Moves
最新推荐文章于 2022-02-25 19:38:17 发布