Reputation: 36446
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?
Upvotes: 3
Views: 170
Reputation: 65
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
Upvotes: 1