dijkstra的算法 – 在c?

前端之家收集整理的这篇文章主要介绍了dijkstra的算法 – 在c?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在过去四天中,我正在努力了解dijkstra的算法.但我不能.我有一个积分的向量.从那我创建了一个成本矩阵.但我不知道如何使dijkstra的算法.资料来源可以在网上,但我不是从计算机科学的背景,所以我不明白他们.我试图做这样的功能
  1. vector<int> dijkstra(costMatrix[][])
  2. {
  3. ....
  4. ....
  5. return vector<int>pathPointindex
  6. }
  7.  
  8. main()
  9. {
  10. vector<Point> availablePoints;
  11. costMatrix[][]=createCostMatrix();
  12. vector<int> indexes=dijikstra(costMatrix)
  13. for(int i=0;i<indexes.size();i++)
  14. cout << "path points are " << availablePoints[indexes[i]] << endl;
  15. }

如果有人,你可以发贴代码.我不懒.但是我的项目一天前已经超过了截止日期.现在我失去了理解逻辑的希望.现在只是我想要的功能. “有需要的人是天使”.

编辑:特别感谢“Loki astari”的出色答案

解决方法

我建议你看看具有非常务实的apporach的 TopCoder教程.
您将需要了解STL优先级队列的工作原理,并确保您的图表中没有任何负边缘权重.

您可以找到体面的完整实现here.您将必须添加路径向量并实现RecoverPath方法,以便从源到宿的路径上获取节点.要使用此解决方案,还需要以下列方式将邻接矩阵转换为邻接列表:

  1. for (int i=0;i<nNodes;i++)
  2. for (int j=0;j<nNodes;j++){
  3. if (costMatrix[i][j] != NO_EDGE_VALUE){
  4. G[i].pb(make_pair(j,costMatrix[i],[j]));
  5. }
  6. }

编辑:如果你的图形很密集,我建议你使用Ford Bellman算法要简单得多,不要太慢.

EDIT2:要计算路径,您应该添加标题

  1. int P[MAX]; /*array with links to parents*/
  2. for(i=0; i<=nodes; i++) P[i] = -1; /*magic unset value*/
  3.  
  4. // dijkstra
  5. while(!Q.empty()) {
  6. ....
  7. if(!F[v] && D[u]+w < D[v]) {
  8. D[v] = D[u] + w;
  9. /*By setting P[v] value we will remember what is the
  10. prevIoUs node on path from source */
  11. P[v] = u; // <-- added line
  12. Q.push(pii(v,D[v]));
  13. }
  14. ...
  15. }

那么你必须添加RecoverPath方法(仅当路径存在时才有效)

  1. vector<int> RecoverPath(int src,int dest){
  2. vector<int> path;
  3. int v = dest;
  4. while (v != src) {
  5. path.push_back(v);
  6. v = P[v];
  7. }
  8. path.push_back(src);
  9. std::reverse(path.begin(),path.end());
  10. return path;
  11. }

猜你在找的C&C++相关文章