骑士移动问题

#include <bits/stdc++.h>
using namespace std;
int step;
int to[8][2] = {-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};//骑士移动的8个方位
int mapp[10][10],endx,endy;
char s1[5],s2[5];
struct node
{
    int start,end,step;
};
int check(int x,int y)          
{
    if(x<0||y<0||x>=8||y>=8||mapp[x][y])
    return 1;
    return 0;
}
int bfs()
{
    int i;
    node p,next,q;
    queue<node>Q;
    p.start=s1[0]-'a';
    p.end=s1[1]-'1';
    p.step=0;
    endx=s2[0]-'a';
    endy=s2[1]-'1';
    memset(mapp,0,sizeof(mapp));
    mapp[p.start][p.end]=1;
    Q.push(p);
    while(!Q.empty())
    {
        q=Q.front();
        Q.pop();
        if(q.start==endx&&q.end==endy)
        return q.step;
        for(i=0;i<8;i++)
        {
            next.start=q.start+to[i][0];
            next.end=q.end+to[i][1];
            if(next.start==endx&&next.end==endy)
            return q.step+1;
            if(check(next.start,next.end))
            continue;
            next.step=q.step+1;
            mapp[next.start][next.end]=1;
            Q.push(next);
        }
    }
    return 0;
}
 int main()
{
    while(cin>>s1>>s2)
    {
        printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());
    }
    return 0;
}

没有更多推荐了,返回首页