简体   繁体   中英

Change depth first algorithm from recursion to iteration

I'm trying to figure out a way to convert the function helper from recursion to iteration, using some form of loop.

I'm actually stumped right now and I'm wondering if any of you guys can help. It's a function created to search if the given start and ending point path exists within a directed graph using a depth first traversal.

def helper(graph, current, visited):
    if current in graph:
        for neighbor in graph[current]:
            if neighbor not in visited:
                visited.append( neighbor )
                helper(graph, neighbor, visited)

def DFS(graph, start, goal):
    if start not in graph and goal not in graph:
        return False
    visited = [start]
    helper(graph, start, visited)
    return goal in visited

The solution is using an explicit stack:

stack = [start]
while len(stack) > 0:
    node = stack.pop()
    for x in graph[node]:
        if x not in visited:
            visited.add(x)
            stack.append(x)

As a side note your code is using a list for visited and this will make things O(n^2) slow, you can use a set instead. Also you could exit immediately on finding the goal if that presence/absence check is all you need from your search.

You will need a stack for depth first (or a queue for breadth first).

def helper(graph, start, visited):
    stack = [ start ]
    while len(stack) > 0:
        current = stack.pop()
        if current in graph:
            for neighbor in graph[current]:
                if neighbor not in visited:
                    visited.append( neighbor )
                    stack.append(neighbor)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM