2012-02-01 169 views
3

如何將使用全局變量的遞歸函數翻譯爲迭代變量?這使用全局變量將全局變量遞歸到迭代

一個例子就是在這裏我想保留的路徑的跟蹤深度優先搜索:

path = [] 

function dfs(node) 
    node.visited = true 
    path.append(node) 

    if node == goal 
     print path 
     stop; 

    for child in node.children 
     if !child.visited 
      dfs(child) 

    path.pop() 

我將如何做到這一點使用迭代和堆棧?

+0

有一個C#示例,可以幫助您在這個鏈接:http://msdn.microsoft.com/en-us/library/bb513869.aspx – NoChance 2012-02-01 03:24:07

+0

你知道如何做到這一點的一個函數,不使用全局變量? – 2012-02-01 04:09:06

+0

@ n.m。當然是。 – tskuzzy 2012-02-01 04:09:36

回答

1

如果你可以擴展Node類,它將如下所示。

function iterative_dfs(start_node) 
    start_node.next = null 
    start_node.visited = true 

    stack = [] 
    stack.push(start_node) 

    while !stack.empty? 
     node = stack.pop 

     if node == goal 
      path = [] 
      while node 
       path.push(node) 
       node = node.next 
      path.reverse 
      print path 
      stop; 

     for child in node.children 
      if !child.visited 
       child.next = node 
       child.visited = true 
       stack.push(child) 

此外,您的代碼有一個錯誤。如果找不到目標,應該彈出節點。

function dfs(node) 
    node.visited = true 
    path.append(node) 

    if node == goal 
     print path 
     stop; 

    for child in node.children 
     if !child.visited 
      dfs(child) 

    path.pop # You need this