我正在嘗試按特定順序列印出 SSSP,但我被卡住了。
假設我有 2 個陣列:
節點 = [0, 1, 2, 3] pred = [-1, 2, 0, 1]
這是我想出的代碼:
void printPath (int currentNode) {
if (pred[currentNode] == -1) {
printf("%d\n", currentNode);
return;
} else {
printf("%d-", currentNode);
return printPath (pred[currentNode]);
}
}
printPath(1);
此代碼將節點 1 的路徑回傳為:1-2-0。當我想要的結果是 0-2-1 時。
用我寫的遞回函式能達到這個結果嗎?
非常感謝!
uj5u.com熱心網友回復:
只需printf在遞回呼叫之后移動節點陳述句即可執行。
int node[] = {0, 1, 2, 3};
int pred[] = {-1, 2, 0, 1};
...
void printPath (int cnode) {
if (-1 == pred[cnode]) {
printf("\n%d", cnode);
return;
} else {
printPath (pred[cnode]);
printf("->%d", cnode);
}
}
...
printPath(1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448946.html
上一篇:在C中的另一個函式內定義遞回函式
下一篇:如何遞回讀取物件的屬性
