搜索专题 T

1、简单描述

骑士在n*n的棋盘上按照图中的走法,从一点到另一点,最少走多少步?

2、思路

#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
bool vis[400][400];
int a[400][400];
int n,sx,sy,ex,ey;
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,step;
};
bool island(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<n)
        return true;
    else
        return false;
}
int bfs()
{
    queue<node>q;
    node start,now,next;
    start.x=sx;
    start.y=sy;
    start.step=0;
    q.push(start);
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        if(now.x == ex && now.y == ey)
            return now.step;
        for(int i = 0; i<8; i++)
        {
            next.x = now.x+dir[i][0];
            next.y = now.y+dir[i][1];
            if(next.x == ex && next.y == ey)
                return now.step+1;
            if (island(next.x,next.y)&&!vis[next.x][next.y])
            {
                next.step=now.step+1;
                vis[next.x][next.y]=true;
                q.push(next);
            }
        }
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        cin>>sx>>sy;
        cin>>ex>>ey;
        memset(vis,false,sizeof(vis));
        vis[sx][sy]=true;
        cout<<bfs()<<endl;
    }
    return 0;
}
广度优先搜索。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值