修改输出图中两个节点之间最短路径的程序



我有一个问题,如何修改这个代码,找到图中两个节点之间的最短路径。这可以正常工作,但是当我的节点之间没有路径程序时,我立即中断,我设置的条件不打印。

void dijkstra2(GRAPH graph, int node,int dest)
{
int previous[MAX];
double distance[MAX]; 
bool Check[MAX]; 
for (int i = 0; i < graph.n; i++) 
{
distance[i] = INT_MAX, Check[i] = false;

}
distance[node] = 0; 
previous[node] = node;
for (int z = 0; z < graph.n - 1; z++)
{
int md = minimumDistance(graph, distance, Check);
Check[md] = true;

for (int o = 0; o < graph.n; o++)
{

if (!Check[o] && graph.ms[md][o] && distance[md] != INT_MAX && distance[md] + graph.ms[md][o] < distance[o])
{
distance[o] = distance[md] + graph.ms[md][o];
previous[o] = md;
if (o == dest) break;
}
}
}
if (node == dest) {
cout << "The start and end nodes are the same. No need to search for a path." << endl;
return;
}

int next = dest;

while (next != node) 
{
cout << next+1 << " <- ";
next = previous[next]; 

}
cout << node + 1;
if (next!=dest) {
cout << "There is no path between the start and end nodes." << endl;
}
}

每次代码访问一个节点时,检查该节点是否是目标节点。如果是,则将标志设置为true。完成后,检查标志,如果没有设置,则打印消息"开始和结束节点之间没有路径"。

相关内容

  • 没有找到相关文章

最新更新