Algorithm 使用堆栈将全局递归转换为迭代
如何将使用全局变量的递归函数转换为迭代函数 其中一个例子是使用深度优先搜索,我希望跟踪路径:Algorithm 使用堆栈将全局递归转换为迭代,algorithm,language-agnostic,recursion,stack,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
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()
我将如何使用迭代和堆栈来实现这一点?如果您可以扩展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)
另外,您的代码有一个bug。如果找不到目标,应弹出节点
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
有一个C#示例可以帮助您进行此链接:您知道如何为不使用全局变量的函数执行此操作吗?那么您知道的methid到底在哪里崩溃了?@n.m:当您试图回溯到各个州时,它会崩溃。我可以将
path
设置为非全局变量,但这会导致非常大的开销。我看不出它是如何导致很大的开销的?e、 里约热内卢的回答没有使用太多的内存或其他开销。