2012-11-28 167 views
1

我試圖在地圖上的兩個點之間找到路徑。遞歸查找路徑

當它從循環中退出並返回權重時,它將轉到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; 
} 
+1

使用調試器來跟蹤程序的流程。 – Kai

+1

只是調試它看看究竟發生了什麼...而且,而不是打破你可以只是返回'重量' – moeTi

+0

我在調試時觀察到這種行爲。當達到return語句時,它返回到else分支並再次調用它自己。 –

回答

2

這就是遞歸的工作原理。您有多個嵌套調用find()在同一時間發生。當最內層調用結束時,下一層內層恢復其操作並繼續執行for循環的下一個操作。

順便說一下,您忽略了遞歸調用返回值find()。這看起來不正確。

+0

所以我需要一個標誌它退出所有調用? –

+0

@locke:這取決於你想要實現的邏輯。 – NPE