지도에서 두 점 사이의 경로를 찾으려고합니다.재귀 경로 찾기
루프에서 빠져 나와 가중치를 반환하면 else 문으로 이동하여 다시 찾기를 호출합니다. 왜 코드가 이것을합니까?
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
그냥 무슨 일이 벌어지는 지 알기 위해 디버깅해라. 또한 깨기 대신에 'weight'를 돌려 줄 수있다. – moeTi
디버깅 중에이 동작을 관찰했다. return 문에 도달하면 else 문으로 돌아가서 다시 자신을 호출합니다. –