poj 1915 http://poj.org/problem?id=1915

/**<  */#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <ctype.h>
#define N 310

using namespace std;

int d[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
int vis[N][N], l, ex, ey;

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

int BFS(int x, int y)
{
    queue<node>Q;
    int i;
    node now, next;
    now.x = x;
    now.y = y;
    now.step = 0;
    vis[now.x][now.y] = 1;
    Q.push(now);
    while(!Q.empty())
    {
        now = Q.front();
        Q.pop();
        if(now.x == ex && now.y == ey)
            return now.step;
        for(i = 0 ; i < 8 ; i++)
        {
            next.x = now.x + d[i][0];
            next.y = now.y + d[i][1];
            next.step = now.step + 1;
            if(next.x >= 0 && next.x < l && next.y >= 0 && next.y < l && !vis[next.x][next.y])
            {
                vis[next.x][next.y] = 1;
                Q.push(next);
            }
        }
    }
    return -1;
}

int main()
{
    int t, sx, sy;
    scanf("%d", &t);
    while(t--)
    {
        memset(vis, 0, sizeof(vis));
        scanf("%d", &l);
        scanf("%d%d", &sx, &sy);
        scanf("%d%d", &ex, &ey);
        if(sx == ex && sy == ey)
            printf("0
");
        else
            printf("%d
", BFS(sx, sy));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/qq2424260747/p/4537671.html