poj 1915 Knight Moves(BFS遍历)


最最基础的bfs 马儿跑啊跑。。。。。

#include<cstdio>

#include<queue>

#include<cstring>

using namespace std;

const int Maxsize = 305;

typedef struct
{
    int x,y;
    int d;
}node;

int cnt;

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

int chess[Maxsize][Maxsize];

int main()
{
    void bfs(node start,node end);
    int k,n,m;
    node start,end;
    scanf("%d",&k);
    while(k--)
    {
        memset(chess,0,sizeof(chess));
        scanf("%d",&cnt);
        scanf("%d %d",&n,&m);
        start.x = n;start.y = m;
        start.d = 0;
        chess[n][m] = 1;
        scanf("%d %d",&n,&m);
        end.x = n;end.y = m;
        bfs(start,end);
    }
    return 0;
}
void bfs(node start,node end)
{
    node pre,cur;
    pre = start;
    queue<node>q;
    q.push(pre);
    while(!q.empty())
    {
        pre = q.front();
        q.pop();
        if(pre.x == end.x && pre.y == end.y)
        {
            printf("%d\n",pre.d);
            return;
        }
        for(int i = 0 ; i < 8 ; i++)
        {
            cur.x = pre.x + dir[i][0];
            cur.y = pre.y + dir[i][1];
            if(chess[cur.x][cur.y])continue;
            if(cur.x < 0 || cur.x >= cnt || cur.y < 0 || cur.y >=cnt )continue;
            chess[cur.x][cur.y] = 1;
            cur.d = pre.d + 1;
            q.push(cur);
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值