POJ 1915 Knight Moves

版权声明: https://blog.csdn.net/qq_40829288/article/details/83716348

Knight Moves

//Knight Moves : http://poj.org/problem?id=1915
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

int l,sx,sy,ex,ey;
bool mark[305][305];
int go[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};

struct node
{
    int x,y,step;
};

void bfs()
{
    memset(mark,0,sizeof(mark));
    mark[sx][sy] = 1;
    queue<node> q;
    node s,n; //n是一个坑点,如果不用n,只用s,会导致下一步的选择对当前步产生影响;
    s.x = sx,s.y = sy,s.step = 0;
    q.push(s);
    while(!q.empty())
    {
        s = q.front();
        q.pop();
        if(s.x == ex&&s.y == ey)
        {
            cout<<s.step<<endl;
            return ;
        }
        for(int i=0;i<8;i++)
        {
            int nx = s.x + go[i][0];
            int ny = s.y + go[i][1];
            if(nx<l&&ny<l&&nx>=0&&ny>=0&&!mark[nx][ny])
            {
                mark[nx][ny] = 1;
                n.x = nx,n.y = ny; // 注意
                n.step = s.step + 1; //注意
                q.push(n);  //注意
            }
        }
    }
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>l>>sx>>sy>>ex>>ey;
        if(sx==ex&&sy==ey)
            cout<<0<<endl;
        else
            bfs();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40829288/article/details/83716348
今日推荐