uva_439 - Knight Moves

/*      题目大意:告诉你国际象棋中马的初始位置和目标位置,算出它的最小步数
 *      解题思路:首先要得知道国际象棋的马如何行动,幸好我玩过,它比中国的马
 * 多走一格,也就是走‘目’字,然后枚举出马的行动方向,用BFS计算出最小步数。
*/
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

#define MAX_ROW         8
#define MAX_COL         8
#define DIR             8

struct Point{
    int x, y, time;
};

int dir[][2] = {
    {-2, -1}, {-2, 1}, {-1, 2}, {1, 2},
    {2, 1}, {2, -1}, {1, -2}, {-1, -2}
};
int target_x, target_y;
bool visited[MAX_ROW+1][MAX_COL+1];

int BFS(int x, int y){
    queue<Point> Q;
    visited[x][y] = true;
    Point p;
    if( p.x == target_x && p.y == target_y ) return 0;
    p.x = x;    p.y = y;    p.time = 0;     Q.push(p);
    while( !Q.empty() ) {
        p = Q.front();  Q.pop();
        if( p.x == target_x && p.y == target_y ) return p.time;
        for(int i = 0; i < DIR; i ++){
            if( p.x+dir[i][0] < 1 || p.x+dir[i][0] > MAX_ROW || p.y+dir[i][1] < 1 || p.y+dir[i][1] > MAX_COL ) continue ;
            if( !visited[p.x+dir[i][0]][p.y+dir[i][1]] ) {
                visited[p.x+dir[i][0]][p.y+dir[i][1]] = true;
                Point tmp_p;
                tmp_p.x = p.x+dir[i][0];
                tmp_p.y = p.y+dir[i][1];
                tmp_p.time = p.time + 1;
                Q.push(tmp_p);
            }
        }
    }
    return -1;
}

int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
        freopen("test.in", "r", stdin);
#endif
    int x, y;
    char tmp_x1, tmp_x2;
    while( ~scanf(" %c%d %c%d", &tmp_x1, &y, &tmp_x2, &target_y) ) {
        x = tmp_x1 - 'a' + 1;      target_x = tmp_x2 - 'a' + 1;
        memset(visited, false, sizeof(visited));
        printf("To get from %c%d to %c%d takes %d knight moves.\n", tmp_x1, y, tmp_x2, target_y, BFS(x, y));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值