poj 1915 Knight Moves(BFS遍历)


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

#include

#include

#include

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;
    queueq;
    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);
        }
    }
}




你可能感兴趣的:(bfs)