使用 BFS 查找最短路径

Using BFS to find the shortest path

本文关键字:最短路径 查找 BFS 使用      更新时间:2023-10-16

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

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

· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · · · · · · · · · ·
· · · 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;
}
我认为

这与你如何计算我们之前的矩阵有关。具体如下代码

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

每当遇到具有当前正在探索的节点的未邀请节点时,都会更新上一个矩阵。但是,请考虑开始时会发生什么。 您将围绕起始位置对每个点进行排队,并将每个节点的上一个矩阵标记为起点。现在,您将探索其他节点。除了起点之外,它的每个邻居都将排队,因为他们都没有被访问过。上一个矩阵中的某些整体将被覆盖。这就是为什么你的路径没有意义。