[英]Modify the program that prints the shortest path between two nodes of a graph
我有一個問題,如何修改這段代碼以找到圖中兩個節點之間的最短路徑。 這可以正常工作,但是當我的節點之間沒有路徑程序時,我會立即中斷,我設置的這個條件不會被打印出來。
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;
}
}
每次您的代碼訪問一個節點時,檢查該節點是否是目的地。 如果是,則設置一個標志為真。 完成后,檢查標志,如果未設置,則打印消息“開始節點和結束節點之間沒有路徑。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.