簡體   English   中英

Floyd-Warshall算法的路徑重構不適用於某些值

[英]Path reconstruction for Floyd-Warshall algorithm doesn't work for some values

我實現了類似http://en.algoritmy.net/article/45708/Floyd-Warshall-algorithm的算法。

 void Graph::floydWarshal()
{
 for (int k = 0; k < weight_matrix.size(); k++)
 {
     for (int i = 0; i < weight_matrix.size(); i++)
     {
         for (int j = 0; j < weight_matrix.size(); j++)
         {
             if (weight_matrix[i][k] != infinity && weight_matrix[k][j] != infinity)
             {
                 int temp = weight_matrix[i][k] + weight_matrix[k][j];
                 if (weight_matrix[i][j] > temp)
                 {
                     weight_matrix[i][j] = temp;
                     predecessors[i][j] = predecessors[k][j];
                 }
             }
         }
     }
 }
}

 void Graph::getPath(int start, int finish, std::vector<int> &path)
 {
  if (start == finish)
  {
      path.push_back(start);
  }
  else if (predecessors[start][finish] == 0)
  {
      path.clear();
      return;
  }
  else
  {
      getPath(start, this->predecessors[start][finish], path);
      path.push_back(finish);
  }
 }

在構造函數中初始化前任

for (int i = 0; i < weight_matrix.size(); i++)
  {
     for (int j = 0; j < weight_matrix[i].size(); j++)
    {
        if (weight_matrix[i][j] != 0 && weight_matrix[i][j] != infinity)
        {
            predecessors[i][j] = i;
        }
        else
        {
            predecessors[i][j] = -1;
        }
    }
 }  

這是長度矩陣

0   2 1  4   inf inf
2   0 7  3   inf inf
1   i 0  5   10  4
4   7 5  0   inf 5
inf 3 10 inf 0  4 
inf inf 4 5  4  0

它僅適用於某些值,例如從頂點5到頂點0的路徑構建(返回5 2 0)。但是從0到5的路徑不構建(返回5)。長度矩陣正確構建

我認為問題出在這一行(它尋找不可能的路徑):

else if (predecessors[start][finish] == 0)

您的節點從零開始索引,因此前任節點在法律上可以等於0。當路由涉及節點零時,您將錯誤地清除路徑。

嘗試使用此代替:

else if (predecessors[start][finish] == -1) 

暫無
暫無

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

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