【BFS】Knight Moves(C++)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/liuzich/article/details/100103205

Description
贝茜和她的表妹在玩一个简化版的国际象棋。棋盘如图所示:

贝茜和表妹各有一颗棋子。棋子每次移一步,且棋子只能往如图所示的八个方向移动。比赛的规则很简单,两个人需要从起点将棋子移到终点,谁能花最少的步数从起点走到终点,就是赢家。为了确保能赢表妹,贝茜希望每次都能算出最少的步数,你能帮助她么
Input
输入起点和终点,用一个空格隔开。(确保起点一定能走到终点)
Output
输入最少的步数。
Sample Input

a1 b2

Sample Output

4

HINT





















和其他的bfs差不多,只是输入变成了char型,转化一下就行了。
代码:


||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

#include <bits/stdc++.h>
using namespace std;
int a1,a2,b1,b2,p[108],q[108],ans[108][108];
int xx[10]= {0,-2,-2,-1,1,2,2,1,-1};
int yy[10]= {0,-1,1,2,2,1,-1,-2,-2};
void bfs(int x,int y) {
    int head=1;
    int tail=1;
    p[1]=x;
    q[1]=y;
    ans[x][y]=1;
    while(head<=tail)
    {
        for(int i=1;i<=8;i++)
        {
            int h=p[head]+xx[i];
            int l=q[head]+yy[i];
            if(ans[h][l]==0&&h>0&&l>0&&h<9&&l<9)
            {
                tail++;
                p[tail]=h;
                q[tail]=l;
                ans[h][l]=ans[p[head]][q[head]]+1;
                if(h==a2&&l==b2)
                {
                    cout<<ans[h][l]-1<<endl;
                    return ;
                }
                 
            }
        }
        head++;
    }
}
int main() {
    char n1,m1,n2,m2;
    cin>>n1>>m1>>n2>>m2;
    memset(ans,0,sizeof(ans));
    a1=n1-'a'+1;
    b1=m1-'0';
    a2=n2-'a'+1;
    b2=m2-'0';
    if(a1==a2&&b1==b2)
    {
        cout<<0<<endl;
        return 0;
    }
    bfs(a1,b1);
  
    return 0;
}

||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||


猜你喜欢

转载自blog.csdn.net/liuzich/article/details/100103205