紫书 UVA439

本文介绍了一个使用广度优先搜索算法来计算国际象棋中骑士从一个位置到另一个位置所需最少移动次数的C++程序实现。通过定义骑士可能的移动方向,并采用队列进行节点扩展,该程序能够有效地找到最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.*/
#include <bits/stdc++.h>

using namespace std;
int m[9][9];
int dir[8][2]= {{-2,1},{-1,2},{1,2},{2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
struct node
{
    int x,y;
    node(int a,int b):x(a),y(b) {}
};
int d[9][9];
int vis[9][9];
char a,b;
int a1,b1;
void bfs(node a)
{
    queue<node> q;
    q.push(a);
    //cout<<a.x<<a.y;
    memset(vis,0,sizeof(vis));
    memset(d,0,sizeof(d));
    vis[a.x][a.y]=1;
    while(!q.empty())
    {
        node p=q.front();
        int x0=p.x;
        int y0=p.y;
        if(p.x==b1&&p.y==b-'a'+1)
            return;
        q.pop();
        for(int i=0; i<8; i++)
        {
            int x1=x0+dir[i][0];
            int y1=y0+dir[i][1];
          //  cout<<x1<<" "<<y1<<endl;;
            if(x1>0&&x1<=8&&y1>0&&y1<=8&&!vis[x1][y1])
            {
                node t(x1,y1);
                d[x1][y1]=d[x0][y0]+1;
                //cout<<d[x1][y1]<<" ";
                if(x1==b1&&y1==(b-'a'+1))
                    return ;
                vis[x1][y1]=1;
                q.push(t);
            }
        }
    }

}
int main()
{

    while(scanf("%c%d %c%d",&a,&a1,&b,&b1)!=EOF)
    {
        getchar();//此处 一定要清除上一次输入的'\n'
        bfs(node(a1,a-'a'+1));
        cout<<"To get from "<<a<<a1<<" to "<<b<<b1<<" takes "<<d[b1][b-'a'+1]<<" knight moves."<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值