我正试图在地图上找到两点之间的路径。
当它从循环中断开并返回权重时,它会转到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;
}
答案 0 :(得分:2)
这就是递归的工作原理。您同时发生了多次find()
嵌套调用。当最里面的调用结束时,next-innermost恢复其操作并继续进行for
循环的下一个操作。
顺便说一句,您忽略了递归调用find()
的返回值。这看起来不对。