POJ_1915_KnightMoves

本文介绍了一个使用广度优先搜索(BFS)解决骑士周游问题的C++实现。该程序通过定义骑士可能的移动方向,并利用队列进行状态扩展来寻找从起点到终点的最短步数。

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

bfs

就是跟马的运动方式一样么……

#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;

const int M=305;

int isu[M][M];

int dx[8]={-2,-1,1,2,2,1,-1,-2};
int dy[8]={-1,-2,-2,-1,1,2,2,1};

queue<int>re;

int tot;

void bfs(int sx,int sy,int ex,int ey,int n)
{

    while(!re.empty())
        re.pop();
    re.push(sx*n+sy);
    isu[sx][sy]=1;
    while(!re.empty())
    {
        int t=re.front();
        re.pop();
        int cx=t/n,cy=t%n;
        //cout<<tot<<" "<<cx<<" "<<cy<<endl;
        for(int i=0;i<8;i++)
        {
            int x=cx+dx[i],y=cy+dy[i];
            if(0<=x&&x<n&&y>=0&&y<n&&!isu[x][y])
            {
                isu[x][y]=isu[cx][cy]+1;
                re.push(x*n+y);
                if(x==ex&&y==ey)
                {
                    tot=isu[x][y];
                    return;
                }
            }
        }
    }
}

void clear()
{
    for (int i = 0; i < M;i++)
    for (int j = 0; j < M; j++)
        isu[i][j] = 0;
}

int main()
{
    int t;
    int n,xj,yj,xm,ym;
    scanf("%d",&t);
    while (t--)
    {
        tot=0;
        scanf("%d%d%d%d%d", &n,&xj,&yj,&xm,&ym);
        if(xj==xm&&yj==ym)
        {
            printf("0\n");
            continue;
        }
        clear();
        bfs(xj,yj,xm,ym,n);
        printf("%d\n", tot-1); //因为不算起点
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值