错误的最短距离BFS算法

Wrong shortest distance BFS algorithm?

本文关键字:BFS 算法 短距离 错误      更新时间:2023-10-16

我正在做这个问题http://community.topcoder.com/stat?c=problem_statement&pm=2915&rd=5853,但是我的程序给出了错误的输出,我尝试了更多的方法,它不能正常工作。我不明白,因为其他人和我一样这么做,而且他们很好。请检查我是否正确执行了BFS?提前谢谢。

#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;
#define P push
#define PP pop();
#define T front();
int mo[][2] = { {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {1, -2}, {-1, 2}, {1, 2} };
int m[8][8];
int BFS(int sy, int sx, int fy, int fx)
{
    queue<int> s;
    m[sy][sx] = 1;
    s.P(sy);
    s.P(sx);
    s.P(0);
    while(!s.empty())
    {
        int d = s.T s.PP
        int x = s.T s.PP
        int y = s.T s.PP
        for(int i=0;i < 8;i++)
        {
            int yy = y + mo[i][0]; 
            int xx = x + mo[i][1];
            if(yy < 0 || yy > 7 || xx < 0 || xx > 7) continue;
            if(m[yy][xx] != -1) continue;
            if(yy == fy && xx == fx) return d + 1;
            m[yy][xx] = 0;
            s.P(yy);
            s.P(xx);
            s.P(d+1);
        }
    }
    return -1;
}
class CaptureThemAll {
public:
    int fastKnight(string knight, string rook, string queen) {
        vector<int> p{knight[0] - 'a', knight[1] - '1', rook[0] - 'a', rook[1] - '1', queen[0] - 'a', queen[1] - '1'};
        memset(m, -1, sizeof(m));
        int a = BFS(p[1], p[0], p[3], p[2]);
        memset(m, -1, sizeof(m));
        int b = BFS(p[1], p[0], p[5], p[4]);
        memset(m, -1, sizeof(m));
        int c = BFS(p[3], p[2], p[5], p[4]);
        return min(a,b) + c;
    } 
};

我认为问题可能是你按了y,x,d所以你的队列将是

Front y  Middle x End d

但是当你弹出前面的元素时,你把它(y)放入一个名为d的变量中。

如果您更改:

    int d = s.T s.PP
    int x = s.T s.PP
    int y = s.T s.PP

    int y = s.T s.PP
    int x = s.T s.PP
    int d = s.T s.PP