Knight Moves BFS POJ 2488

9 篇文章 0 订阅

//要注意清空队列(全局)或者写进函数里 


#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;

const int MAX = 8;

int dirx[MAX] = {-2,-2,2,2,-1,-1,1,1}, diry[MAX] = {1,-1,-1,1,2,-2,-2,2};
char sx, sy, ex, ey;

struct Point{
    int x, y;
    int step;
    bool flag;
    string path;

    Point(){
        x = 0;
        y = 0;
        step = 0;
        flag = false;
        path = "";
    }
/*
    Point(int a, int b, bool sign){
        x = a;
        y = b;
        flag = sign;
    }
    */
};

int Judge(Point t, int ex, int ey)
{
    if(t.x == ex && t.y == ey){
        return 1;
    }
    return 0;
}


int Check(Point t)
{
    if(t.x <= 0 || t.y <= 0 || t.y > MAX || t.x > MAX){
        return 0;
    }
    return 1;

}

void bfs(int s1, int s2, int e1, int e2)
{
    queue<Point> q;

    Point tmp;
    tmp.x = s1;
    tmp.y = s2;
    tmp.step = 0;
    tmp.flag = true;
    q.push(tmp);

    while(!q.empty()){
        tmp = q.front();
        q.pop();

        if(Judge(tmp, e1, e2)){

            printf("To get from %c%c to %c%c takes %d knight moves.\n", sx, sy, ex, ey, tmp.step);

            return;
        }

        for(int i=0; i<8; i++){
            Point tmp2;
            tmp2.x = tmp.x+dirx[i];
            tmp2.y = tmp.y+diry[i];
            tmp2.step = tmp.step+1;

            if(Check(tmp2) && !tmp2.flag){
                tmp2.flag = true;
                q.push(tmp2);
            }

        }
    }
}

int main()
{
    while(cin >> sx >> sy >> ex >> ey){

        int s1 = sx-'a', s2 = sy-'0', e1 = ex-'a', e2 = ey-'0';
//        cout << s1+1 << " " << s2 << " "<< e1+1 << " "<< e2 << endl;
        bfs(s1+1, s2, e1+1, e2);
    }
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值