poj 1915 双向 BFS 利用数组 a[x][y] = a[cp.x][cp.y] + 1; b[x][y] = b[cp.x][cp.y] + 1;保留步数

#include<iostream>
#include<queue>


using namespace std;


struct point
{
    int x, y;
};
point bufa[8] =
{
    {-2, 1}, {-1, 2}, {1, 2}, {2, 1},
    {2, -1}, {1, -2}, {-1, -2}, {-2, -1}
};


int n, a[305][305], b[305][305];


int rule(int x,int y)//判断是否符合棋盘的条件
{
    if (x >= 0 && x < n && y >= 0 && y < n)
        return 1;
    return 0;
}


int dbfs(int sx, int sy, int tx, int ty)
{
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            a[i][j] = b[i][j] = -1;    //  未被访问过


    a[sx][sy] = b[tx][ty] = 0;


    queue <point> l, r;
    point sp = { sx, sy };
    point tp = { tx, ty };
    l.push(sp);
    r.push(tp);


    point cp;
    while (!(l.empty()&&r.empty()))
    {
        if (!l.empty())//正向广搜
        {
            cp = l.front();
            l.pop();
           
            for (int i = 0; i < 8; i++)
            {
                int x = cp.x + bufa[i].x;
                int y = cp.y + bufa[i].y;
                if (rule(x, y))
                {
                    if (a[x][y] == -1)               //  未被访问过 
                    {
                        a[x][y] = a[cp.x][cp.y] + 1;
                        point np = { x, y };
                        l.push(np);
                    }
                    if (b[x][y] != -1)//表明搜索过程相交
                        return a[x][y] + b[x][y];
                }
            }
        }
        if (!r.empty())//反向广搜
        {
            cp = r.front();
            r.pop();
            for (int i = 0; i < 8; i++)
            {
                int x = cp.x + bufa[i].x;
                int y = cp.y + bufa[i].y;
                if (rule(x, y))
                {
                    if (b[x][y] == -1)
                    {
                        b[x][y] = b[cp.x][cp.y] + 1;
                        point np = { x, y };
                        r.push(np);
                    }
                    if (a[x][y] != -1)//表明搜索过程相交
                        return a[x][y] + b[x][y];
                }
            }
        }
    }
}


int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        cin >> n;
        int sx, sy, tx, ty;
        cin >> sx >> sy >> tx >> ty;


        if (sx == tx && sy == ty)
            cout << 0 << endl;
        else
            cout << dbfs(sx, sy, tx, ty) << endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/2014acm/p/3900627.html