hdu1372Knight Moves

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

一个可以走8个方向。BFS求最短路

代码:

#include 
#include 
#include 

using namespace std;

int v[10][10];

int stx,sty,enx,eny;

struct node{
    int x,y;
    int step;
};
node ans;
node t;
int dx[] = {-1,-2,-2,-1,1,2,2,1};
int dy[] = {-2,-1,1,2,2,1,-1,-2};

void bfs()

{
    memset(v,0,sizeof(v));
    queue q;
    node f;
    f.x = stx;
    f.y = sty;
    f.step = 0;
    q.push(f);
    while(!q.empty())
    {
        node h = q.front();
        q.pop();
        if(h.x == enx && h.y == eny)
        {
            ans = h;
            return ;
        }
        for(int i = 0 ;i < 8;++i)
        {
            int tx = h.x + dx[i];
            int ty = h.y + dy[i];
            if(tx >= 1 && tx <= 8 && ty >= 1 && ty <= 8 && !v[tx][ty])
            {
                t.x = tx;
                t.y = ty;
                t.step = h.step + 1;
                q.push(t);
                v[tx][ty] = 1;
            }
        }
    }
}
int main()

{
    char s[5],s1[5];
    while(~scanf("%s%s",s,s1))
    {
        stx = s[1] - '0';
        sty = s[0] - 'a' + 1;
        enx = s1[1] -'0';
        eny = s1[0] - 'a' + 1;
        if(stx == enx && sty == eny)
        {
            printf("To get from %s to %s takes 0 knight moves.\n",s,s1);
            continue;
        }
        bfs();
        printf("To get from %s to %s takes %d knight moves.\n",s,s1,ans.step);
    }
    return 0;
}

你可能感兴趣的:(bfs)