HDU 1372 Knight Moves (BFS)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372


简单的BFS。即给定马的起点和终点(走的方式和象棋一样),求最短的路径。关键是要弄清楚马的行进方向的顺序,即从右上第一个顺时针过来。

代码:

</pre><pre name="code" class="cpp"><span style="color:#000000;">#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int sx,sy,ex,ey,a[10][10],use[10][10];
int dx[8]= {-2,-1,1,2,2,1,-1,-2},dy[8]= {1,2,2,1,-1,-2,-2,-1};
struct point
{
    int x,y,step;
};
queue<point> Q;
int bfs(int x,int y)
{
    point Start,New;
    Start.x=x;
    Start.y=y;
    Start.step=0;
    Q.push(Start);
    while(!Q.empty())
    {
        Start = Q.front();
        Q.pop();
        if(Start.x==ex&&Start.y==ey)
            return Start.step;
        for(int i=0; i<8; i++)
        {
            New.x=Start.x+dx[i];
            New.y=Start.y+dy[i];
            New.step=Start.step;
            if(New.x>0&&New.y>0&&New.x<9&&New.y<9&&!use[New.x][New.y])
            {
                use[New.x][New.y]=1;
                New.step=Start.step+1;
                Q.push(New);
            }
        }
    }
}
int main()
{
    char S[10],E[10];
    while(scanf("%s %s",S,E)!=EOF)
    {
        while(!Q.empty())
            Q.pop();
        memset(use,0,sizeof(use));
        sx=S[0]-'a'+1,sy=S[1]-'0';
        ex=E[0]-'a'+1,ey=E[1]-'0';
        use[sx][sy]=1;
        printf("To get from %s to %s takes %d knight moves.\n",S,E,bfs(sx,sy));
    }
    return 0;
}
</span>



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值