我試圖在地圖上的兩個點之間找到路徑。遞歸查找路徑
當它從循環中退出並返回權重時,它將轉到else語句並再次調用find。爲什麼代碼會這樣做?
public int find() throws LinkException {
Node currentNode = map.getNode(origin);
int weight = 0;
return find(currentNode, null, weight);
}
private int find(Node currentNode, Node pastNode, int weight) throws LinkException {
for (Node futureNode : currentNode.getLinks()) {
if (currentNode == futureNode || futureNode == pastNode) {
continue;
}
weight += currentNode.getLink(futureNode).getWeight();
pastNode = currentNode;
currentNode = futureNode;
if (currentNode.getName().equals(destination)) { // Here we reach the destination
break;
} else {
find(currentNode, pastNode, weight);
}
}
return weight;
}
使用調試器來跟蹤程序的流程。 – Kai
只是調試它看看究竟發生了什麼...而且,而不是打破你可以只是返回'重量' – moeTi
我在調試時觀察到這種行爲。當達到return語句時,它返回到else分支並再次調用它自己。 –