HDU1372 Knight Moves (BFS)

题意分析

在国际象棋棋盘中给出两个点,问马从一个点到另一个点最少需要跳几步。

国际象棋中的马和中国象棋的马没有什么区别,只是没有蹩马腿这一说。

然后就是裸地BFS了。

代码总览

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int nmax = 10;
const int ntx[] = {1,1,-1,-1,2,2,-2,-2};
const int nty[] = {2,-2,2,-2,1,-1,1,-1};
int sx,sy,ex,ey;
bool visit[nmax][nmax];
char sta[nmax],ed[nmax];
void cope(){
    sx = sta[0] - 'a';
    sy = sta[1] - '1';
    ex = ed[0] - 'a';
    ey = ed[1] - '1';
}
bool legal(int x ,int y){
    if(x <0 || x >= 8 || y<0 || y>=8) return false;
    else return true;
}
int bfs(){
    queue<int> q;
    int x = sx, y = sy , step = 0;
    q.push(x);q.push(y);q.push(step);
    while(!q.empty()){
        x = q.front();q.pop();
        y = q.front();q.pop();
        step = q.front();q.pop();
        visit[x][y]= true;
        if(x == ex && y == ey) return step;
        for(int i = 0;i<8;++i){
            int xx = x + ntx[i];
            int yy = y + nty[i];
            if(legal(xx,yy) && !visit[xx][yy]){
                q.push(xx);q.push(yy);q.push(step+1);
            }
        }
    }
    return -1;
}
int main(){
    while(scanf("%s",sta) != EOF){
        scanf("%s",ed);
        memset(visit,0,sizeof visit);
        cope();
        int ans = bfs();
        printf("To get from %s to %s takes %d knight moves.\n",sta,ed,ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值