使用stack将带有全局变量的递归转换为迭代

时间:2012-02-01 03:17:28

标签: algorithm language-agnostic recursion stack

如何将使用全局变量的递归函数转换为迭代函数?

这方面的一个例子是使用深度优先搜索,我想跟踪路径:

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()

如何使用迭代和堆栈执行此操作?

1 个答案:

答案 0 :(得分: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