2011-10-22 84 views
1

我想實現Breadth-first search algorithm,以便找到兩個頂點之間的最短距離。我開發了一個Queue對象來保存和檢索對象,並且我有一個二維數組來保存兩個給定頂點之間的邊的長度。我試圖填充一個二維數組來保存兩個頂點之間最短的距離。圖算法的C++實現

但是,我遇到的問題是,無論我要求哪兩個頂點的最短距離,返回0。這是我的算法實現;如果你能讓我走上正確的軌道,並幫助我找出問題,那就太棒了。

for (int i = 0; i < number_of_vertex; i++) 
//For every vertex, so that we may fill the array 
{ 
    int[] dist = new int[number_of_vertex]; 
    //Initialize a new array to hold the values for the distances 

for (int j = 0; x < number_of_vertex; j++) 
{ 
    dist[j] = -1; 
    //All distance values will be set to -1 by default; this will be changed later on 
} 

    dist[i] = 0; //The source node's distance is set to 0 (Pseudocode line 4) 

    myQueue.add(i); //Add the source node's number to the queue (Pseudocode line 3) 

    while (!myQueue.empty()) //Pseudocode line 5 
    { 
     int u = myQueue.eject(); //Pseudocode line 6 

     for (int y = 0; y < number_of_vertex; y++) //Pseudocode line 7 
     { 
      if (edge_distance(u,y) > 0) 
      { 
       if (dist[y] == -1) 
       { 
        myQueue.add(y); 
        dist[y] = dist[u] + 1; 
        shortest_distance[i][u] = dist[y]; 
       } 
      }  
     }     
    } 
} 
+0

有什麼不對的std ::隊列? –

+0

什麼都沒有;我剛剛有一個自定義的隊列類,這個類是我在一年前或之前爲某個任務做出的。它的工作完美無缺,所以我喜歡,呃,爲什麼不呢? –

+0

我無法理解你的循環,你應該擁有所有距離的數組,而不僅僅是一個頂點,每次你在啓動時將節點的距離設置爲零,當你要獲得輸出時?寫完整的代碼(你的cout在哪裏?)。 –

回答

1

好吧......我想這個問題是關於所使用的算法和有關使用的術語。

「爲了找到兩個頂點之間的最短距離」,您是指連接圖中兩個頂點之間的最短路徑?

您試圖編寫的算法是Dijkstra算法(這是名稱)。

http://www.cs.berkeley.edu/~vazirani/algorithms/chap4.pdf

+0

我不認爲這是使用算法的問題;我應該能夠用這個算法解決問題,而不必訴諸另一個。 至於距離,edge_distance [] []數組返回任意兩個頂點之間的距離; shortest_distance [] []數組就是我試圖用算法填充(所以不只是距離,而是最短距離)。 –