簡體   English   中英

使用BFS查找最短路徑

[英]Using BFS to find the shortest path

正如標題所言,我正在嘗試尋找一個最短路徑來移動一個單元到近東控制點(就像它是寶物一樣)。 我試圖使用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;
 }

每當遇到未邀請的節點和當前正在瀏覽的節點時,便會更新前一個矩陣。 但是,請考慮一下開始時會發生什么。 您將圍繞起點的每個點排隊,並將每個節點的先前矩陣標記為起點。 現在,您將探索其他節點。 它的每個鄰居都將被排隊,除了起點之外,因為沒有人被訪問過。 先前矩陣中的某些整體將被覆蓋。 這就是為什么您的路徑沒有意義的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM