首页 > 代码库 > bfs Knight Moves

bfs Knight Moves

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
#define maxn 300
int steps=0;
const int next[8][2]={{-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2}};
struct point
{
    int x;
    int y;
};
int book[maxn][maxn];
queue<point> q;
void bfs(point a,point b,int l)
{
    steps=0;
    while(!q.empty())
        q.pop();
    memset(book,0,sizeof(book));
    book[a.x][a.y]=1;
    q.push(a);
    while(!q.empty())
    {
        int que_size=q.size();
        while(que_size--)
        {
            point head=q.front();
            q.pop();
            if(head.x==b.x&&head.y==b.y)
                return;
            point t;
            for(int i=0;i<8;i++)
            {
                t.x=head.x+next[i][0];
                t.y=head.y+next[i][1];
                if(t.x>=l||t.x<0||t.y>=l||t.y<0)
                    continue;
                if(book[t.x][t.y]==0)
                {
                  q.push(t);
                  book[t.x][t.y]=1;
                }

            }

        }
        steps++;
    }
}
int main()
{
    int cases;
    cin>>cases;
    point s,e;
    int l;
    while(cases--)
    {
        cin>>l>>s.x>>s.y>>e.x>>e.y;
        bfs(s,e,l);
        cout<<steps<<endl;
    }
}

 可以自行理解,没啥好讲的,在脑子里自己跑跑就懂了。

bfs Knight Moves