POJ 1915 Knight Moves(广搜)

代码:

#include<stdio.h>
#include<string.h>
#include<queue>

using namespace std;

struct node
{
    int x;
    int y;
    int num;
}temp,base;

int fx[8]={2,1,-2,-1,-1,1,-2,2};
int fy[8]={1,2,-1,-2,2,-2,1,-1};
int book[305][305];
int n;
int startx,starty;
int endx,endy;

int bfs(int x,int y)
{
    queue<node>q;
    base.x=x;
    base.y=y;
    base.num=0;
    q.push(base);

    while(!q.empty())
    {
        temp=q.front();
        q.pop();
        if(temp.x==endx&&temp.y==endy)
            return temp.num;
        for(int i=0;i<8;i++)
        {
            base.x=temp.x+fx[i];
            base.y=temp.y+fy[i];
            if(base.x>=0&&base.x<n&&base.y>=0&&base.y<n&&book[base.x][base.y]==0)
            {
                base.num=temp.num+1;
                book[base.x][base.y]=1;
                q.push(base);
            }
        }
    }
    return 0;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        memset(book,0,sizeof(book));
        scanf("%d%d%d%d",&startx,&starty,&endx,&endy);
        book[startx][starty]=1;
        printf("%d\n",bfs(startx,starty));
    }
}


你可能感兴趣的:(POJ 1915 Knight Moves(广搜))