POJ 1915 Knight Moves

本文介绍了一种解决骑士在棋盘上从起点到终点最短路径问题的算法。使用了广度优先搜索(BFS)策略,通过定义状态转移矩阵和节点结构,实现了对骑士可能的八种移动方向的遍历。在给定棋盘大小和起始、结束位置的情况下,算法能够高效地计算出最短步数。

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

Knight Moves

//Knight Moves : http://poj.org/problem?id=1915
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

int l,sx,sy,ex,ey;
bool mark[305][305];
int go[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};

struct node
{
    int x,y,step;
};

void bfs()
{
    memset(mark,0,sizeof(mark));
    mark[sx][sy] = 1;
    queue<node> q;
    node s,n; //n是一个坑点,如果不用n,只用s,会导致下一步的选择对当前步产生影响;
    s.x = sx,s.y = sy,s.step = 0;
    q.push(s);
    while(!q.empty())
    {
        s = q.front();
        q.pop();
        if(s.x == ex&&s.y == ey)
        {
            cout<<s.step<<endl;
            return ;
        }
        for(int i=0;i<8;i++)
        {
            int nx = s.x + go[i][0];
            int ny = s.y + go[i][1];
            if(nx<l&&ny<l&&nx>=0&&ny>=0&&!mark[nx][ny])
            {
                mark[nx][ny] = 1;
                n.x = nx,n.y = ny; // 注意
                n.step = s.step + 1; //注意
                q.push(n);  //注意
            }
        }
    }
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>l>>sx>>sy>>ex>>ey;
        if(sx==ex&&sy==ey)
            cout<<0<<endl;
        else
            bfs();
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值