根据给出的代码,可以实现如下的输出函数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助手提供,问题来源于学员提问