ZBLOG

根据代码 void Dijkstra(ALDirNetwork& graph, int v0, int* dist, int* path) { int mindist, infinity = graph.GetInfinity(); int v, u; for (v = 0; v < graph.GetVexNum(); v++) { dist[v] = graph.GetWeight(v0, v); if (dist[v] == infinity) ...

根据给出的代码,可以实现如下的输出函数OutputShortestPath来输出最短路径和距离:

  1. void OutputShortestPath(ALDirNetwork<char, int>& graph, int v, int* dist, int* path)
  2. {
  3. char vertex = graph.GetValue(v);
  4. for (int i = 0; i < graph.GetVexNum(); i++) {
  5. if (i != v) {
  6. char destVertex = graph.GetValue(i);
  7. std::cout << "The shortest path between " << vertex << " and " << destVertex << " is: ";
  8. // 输出路径
  9. std::stack<int> stack;
  10. int index = i;
  11. while (path[index] != -1) {
  12. stack.push(index);
  13. index = path[index];
  14. }
  15. std::cout << vertex;
  16. while (!stack.empty()) {
  17. std::cout << " " << graph.GetValue(stack.top());
  18. stack.pop();
  19. }
  20. // 输出距离
  21. if (dist[i] == graph.GetInfinity()) {
  22. std::cout << "\nThere is no path between " << vertex << " and " << destVertex;
  23. } else {
  24. std::cout << "\nThe distance is: " << dist[i];
  25. }
  26. std::cout<<std::endl;
  27. }
  28. }
  29. }

你可以在主程序中调用该函数,传入图、起点、最短距离数组和路径数组来进行输出。注意要先调用Dijkstra算法函数获取最短距离和路径。

希望对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9273

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?