繁体   English   中英

错误的最短距离BFS算法?

[英]Wrong shortest distance BFS algorithm?

我正在做这个问题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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM