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来输出最短路径和距离:

void OutputShortestPath(ALDirNetwork<char, int>& graph, int v, int* dist, int* path)
{
    char vertex = graph.GetValue(v);
    
    for (int i = 0; i < graph.GetVexNum(); i++) {
        if (i != v) {
            char destVertex = graph.GetValue(i);
            std::cout << "The shortest path between " << vertex << " and " << destVertex << " is: ";
            
            // 输出路径
            std::stack<int> stack;
            int index = i;
            while (path[index] != -1) {
                stack.push(index);
                index = path[index];
            }
            
            std::cout << vertex;
            while (!stack.empty()) {
                std::cout << " " << graph.GetValue(stack.top());
                stack.pop();
            }
            
            // 输出距离
            if (dist[i] == graph.GetInfinity()) {
                std::cout << "\nThere is no path between " << vertex << " and " << destVertex;
            } else {
                std::cout << "\nThe distance is: " << dist[i];
            }
            
          	std::cout<<std::endl;
        }
    }
}

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

希望对你有所帮助!


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?