我想實現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];
}
}
}
}
}
有什麼不對的std ::隊列? –
什麼都沒有;我剛剛有一個自定義的隊列類,這個類是我在一年前或之前爲某個任務做出的。它的工作完美無缺,所以我喜歡,呃,爲什麼不呢? –
我無法理解你的循環,你應該擁有所有距離的數組,而不僅僅是一個頂點,每次你在啓動時將節點的距離設置爲零,當你要獲得輸出時?寫完整的代碼(你的cout在哪裏?)。 –