uva 439 - Knight Moves

//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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值