C++ 用BFS寻找最短路径

C++ 用BFS寻找最短路径,c++,C++,正如标题所说,我正试图找到一个单位移动到最近控制点的最短路径(就像它是一个宝藏或其他东西)。我试图使用BFS找到这条路径,但它没有给出最短的路径。例如: 如果我们有类似的东西(其中X是起始位置,K是一个控制点) 我的代码给出了以下路径: · · · · · · · · · · · · · · · · · · · · · · · · · · - - - · · · · · · · · · | X | · · · · · · · · · | | - · · · · · · · · · | · · ·

正如标题所说,我正试图找到一个单位移动到最近控制点的最短路径(就像它是一个宝藏或其他东西)。我试图使用BFS找到这条路径,但它没有给出最短的路径。例如:

如果我们有类似的东西(其中X是起始位置,K是一个控制点)

我的代码给出了以下路径:

· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · - - - · · · · · · ·
· · | X | · · · · · · ·
· · | | - · · · · · · ·
· · | · · · · · · · · ·
· · | · · · · · · · · ·
· · · | · · · · · · · ·
· · · | - K · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · · 
但我不明白为什么它会给我这些额外的动作。有人能看出我做错了什么

typedef pair<int,int> Coord;
typedef vector< vector<bool> > VIS; 
typedef vector<vector< Coord> > Prev;
const int X[8] = { 1, 1, 0, -1, -1, -1,  0,  1 };
const int Y[8] = { 0, 1, 1,  1,  0, -1, -1, -1 };


list<Coord> BFS2(int x, int y, VIS& visited, Prev& p) {
    queue<Coord> Q;

    Coord in;
    in.first = x; in.second = y;

    Q.push(in);
    bool found = false;
    Coord actual;
    while( not Q.empty() and not found){   
       actual = Q.front();         
       Q.pop();
       int post = who_post(actual.first, actual.second); //It tells if we're in a control point or not(0 == if we are not in the C.point)
       if(post != 0){
          found = true;                
       }
       else {
           visited[actual.first][actual.second]=true; 
           for( int i = 0; i < 8; i++){
                  int nx = X[i] + actual.first;      
                  int ny = Y[i] + actual.second;
                //The maze is 60x60, but the borders are all mountains, so we can't access there
                if(nx>=1 and nx<59 and ny>=1 and ny<59 and not visited[nx][ny]){
                    Coord next;
                    next.first = nx; next.second = ny;
                    Q.push(next);
                    p[nx][ny] = actual;
                }
            }
        }
    }
    list<Coord> res;

    while(actual != in){
        res.push_back(actual);
        actual = p[actual.first][actual.second];
    }
    res.reverse();
    return res;
}
typedef对坐标;
typedef向量VIS;
typedef向量>Prev;
常量int X[8]={1,1,0,-1,-1,-1,0,1};
常量int Y[8]={0,1,1,1,0,-1,-1,-1};
列表BFS2(内部x、内部y、可视和访问、上一个和下一个){
队列Q;
合作;
in.first=x;in.second=y;
Q.推(入);
bool-found=false;
实际协调;
while(非Q.empty()且未找到){
实际=Q.前();
Q.pop();
int post=who_post(actual.first,actual.second);//它告诉我们是否在控制点(0==如果我们不在C.point)
如果(post!=0){
发现=真;
}
否则{
访问[actual.first][actual.second]=true;
对于(int i=0;i<8;i++){
int nx=X[i]+实际值.first;
int ny=Y[i]+实际秒数;
//迷宫是60x60,但是边界都是山,所以我们不能进入那里

如果(nx>=1,nx=1,ny我认为这与你如何计算我们之前的矩阵有关

 if(nx>=1 and nx<59 and ny>=1 and ny<59 and not visited[nx][ny]){
     ...
     p[nx][ny] = actual;
 }
如果(nx>=1且nx=1且ny
 if(nx>=1 and nx<59 and ny>=1 and ny<59 and not visited[nx][ny]){
     ...
     p[nx][ny] = actual;
 }