POJ 1915 Knight Moves

一道简单的BFS搜索题。

#include <stdio.h>
#include <string.h>
int x1,y1,x2,y2,m;
int z[400][400];
int h[8][2]={{-2,-1},{-1,-2},{-1,2},{-2,1},{1,2},{2,1},{1,-2},{2,-1}};
struct sa
{
    int x,y,step;
}data[90001];
int bfs(int x,int y)
{
    if (x==x2&&y==y2) return 0;
    int r=0,l=0;
    data[r].x=x;
    data[r].y=y;
    data[r++].step=0;
    while (l<r)
    {
        sa now,next;
        now.x=data[l].x;
        now.y=data[l].y;
        now.step=data[l++].step;
        for (int b=0;b<8;b++)
        {
            next.x=now.x+h[b][0];
            next.y=now.y+h[b][1];
            next.step=now.step+1;
            if (next.x>=0&&next.x<m&&next.y>=0&&next.y<m&&z[next.x][next.y]==0)
            {
                if (next.x==x2&&next.y==y2) return next.step;
                z[next.x][next.y]=1;
                data[r].x=next.x;
                data[r].y=next.y;
                data[r++].step=next.step;
            }
        }
    }
    return -1;
}
int main()
{
    int n,count;
    scanf("%d",&n);
    while (n--)
    {
        scanf("%d",&m);
        scanf("%d%d",&x1,&y1);
        scanf("%d%d",&x2,&y2);
        z[x1][y1]=1;
        memset(z,0,sizeof(z));
        count=bfs(x1,y1);
        printf("%d\n",count);
        count=0;
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值