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>



你可能感兴趣的:(C++,基础,遍历,bfs,广搜)