How would you translate a recursive function that uses global variables to an iterative one?

One example of this is using depth-first search where I want to keep track of the path:

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

How would I do this using iteration and a stack?

preguntado el 01 de febrero de 12 a las 03:02

Do you know how to do it for a function that does not use globals? -

So where exactly the methid you know is breaking down? -

@n.m: It breaks down when you're trying to backtrack through the states. I could make `path` a non-global variable, but that would incur a very large overhead. -

I can't see how it causes to large overhead? e.g rio's answer doesn't used too many memory or other overheads. -

## 1 Respuestas

If you could extend the Node class, it will be like below.

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

Also, your code has a bug. You should pop the node if you couldn't find the goal.

``````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
``````

Respondido 01 Feb 12, 09:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.