bfs简单题----Knight Moves(hdu 1372)

题目大意:骑士移动,以象棋中的“马走日”移动的方式一样。给你一个方阵,以字母a~h代表列,以数字1~8代表行。

输入两个字符串,一个代表起点,一个代表终点,求在方阵范围里从起点到终点至少要走多少步。

#include <iostream>
#include <string>
#include <queue>
using namespace std;
int s1,s2,e1,e2;
string a,b;
int mark[10][10];
int rule[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node
{
    int x,y,step;
};
int bfs()
{
    queue<node> que;
    node pre,next;
    pre.x=s1;
    pre.y=s2;
    pre.step=0;
    mark[pre.x][pre.y]=1;
    que.push(pre);
    while(!que.empty())
    {
        pre=que.front();
        que.pop();
        if(pre.x==e1&&pre.y==e2) {return pre.step; break;}
        for(int i=0;i<8;i++)
        {
            next=pre;
            if(next.x+rule[i][0]>0&&next.x+rule[i][0]<9 
                &&next.y+rule[i][1]>0&&next.y+rule[i][1]<9&&mark[next.x+rule[i][0]][next.y+rule[i][1]]==0 )
            {
                next.x+=rule[i][0];
                next.y+=rule[i][1];
                next.step++;
                mark[next.x][next.y]=1;
                que.push(next);
            }
        }
    }
    return 0;
}
int main()
{
    while(cin>>a>>b)
    {
        s1=a[0]-'a'+1;
        s2=a[1]-'0';
        e1=b[0]-'a'+1;
        e2=b[1]-'0';
        memset(mark,0,sizeof(mark));
        cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值