如何打印从一个节点到另一个节点的所有可能路径的成本?
发布时间:2022-06-25 07:31:31 269
相关标签:
我想打印从源节点到目标节点的所有路径,以及这些路径的成本。
到目前为止,我有以下代码:
// Find all paths from source to destination.
void search(Graph* graph, int src, int dst)
{
// Mark the current node and store it in path.
graph->visited[src] = true;
graph->path[graph->index] = src;
graph->index++;
// If current vertex is same as destination.
if (src == dst)
{
for (int i = 0; i < graph->index; i++)
{
if (i != graph->index - 1)
{
printf("%d -> ", graph->path[i] + 1);
}
else
{
printf("%d = %.3f\n\t", graph->path[i] + 1, graph->distance);
}
}
}
else
{
// For all unvisited vertices adjacent to current vertex.
for (Node* adj = graph->array[src]; adj; adj = adj->next)
{
if (!graph->visited[adj->vertex])
{
graph->distance += adj->weight;
search(graph,adj->vertex, dst);
}
}
}
// Remove current vertex from path and mark it as unvisited.
graph->index--;
graph->distance -= graph->array[graph->index]->weight;
graph->visited[src] = false;
}
它可以部分工作,正确地打印路径和成本,直到需要返回到以前的节点。此时,程序以错误代码结束。
下面是一个如何发生的示例:
Paths from 1 to 5:
1 -> 3 -> 5 = 39.576
1 -> 3 -> 2 -> 5 = 46.172
1 -> 3 -> 2 -> 4 -> 5 = 52.768
Process finished with exit code -1073741819 (0xC0000005)
预期的结果是算法返回节点2,并从那里搜索其他路径。然后按如下方式打印结果:
Paths from 1 to 5:
1 -> 3 -> 5 = 39.576
1 -> 3 -> 2 -> 5 = 46.172
1 -> 3 -> 2 -> 4 -> 5 = 52.768
1 -> 2 -> 5 = 39.576
1 -> 2 -> 4 -> 5 = 46.172
Process finished with exit code 0
有人能帮我解决这个问题吗?
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报