poj 2243 骑士游历2

#include <iostream>
#include <queue>
#include <cstring>

namespace {
    using namespace std;

    struct POS_S {
        POS_S(int, int);
        
        int x, y;
    };

    POS_S::POS_S(int pos_x, int pos_y)
    {
        x = pos_x; y = pos_y;
    }

    #define L_MAX 8
    unsigned char moves[L_MAX][L_MAX];

    #define MOVES_INFINITE 64

    int src_x, src_y, dst_x, dst_y;
    int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2}, dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};

    inline bool goal(int x, int y)
    {
        return (x==dst_x) && (y==dst_y);
    }

    inline bool onboard(int x, int y)
    {
        return (0<=x && x<8) && (0<=y && y<8);
    }

    inline bool visited(int x, int y)
    {
        return moves[x][y] != MOVES_INFINITE;
    }

    inline void moves_reset()
    {
        memset(moves, MOVES_INFINITE, sizeof(moves));
    }

    int knight_moves(int sx, int sy)
    {
        moves_reset();
        moves[sx][sy] = 0;

        queue<POS_S> Q;
        Q.push(POS_S(sx, sy));
        while (!Q.empty())
        {
            POS_S pos = Q.front(); Q.pop();

            if (goal(pos.x, pos.y))
            {
                return moves[pos.x][pos.y];
            }

            for (int i=0; i<8; i++)
            {
                int nx = pos.x + dx[i];
                int ny = pos.y + dy[i];
                if (onboard(nx, ny) && !visited(nx, ny))
                {
                    moves[nx][ny] = moves[pos.x][pos.y] + 1;
                    Q.push(POS_S(nx, ny));
                }
            }
        }

        return MOVES_INFINITE;
    }
}

int main()
{
    char c;
    while (cin>>c)
    {
        src_y = c - 'a';
        cin >> src_x; src_x--;

        cin >> c;
        dst_y = c - 'a';
        cin >> dst_x; dst_x--;

        cout << "To get from " << char(src_y+'a') << (src_x+1)
             << " to " << char(dst_y+'a') << (dst_x+1) << " takes "
             << knight_moves(src_x, src_y) <<  " knight moves." << endl;
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值