Search code examples
pythonalgorithmrecursionsearchdepth-first-search

Exit DFS Recursion When Target Vertex Is Found And Return Path


I have made a recursive DFS algorithm which can return a path when a target is found. Notice that I'm taking advantage of recursion and I try to utilize as less memory as possible in path saving. When the target is found, it is guaranteed that path will contain the correct path. But then the DFS must completely stop or else I cannot return a correct list due to the pop()s after. Temporary solution is a global list result. Is there any way to:

  1. Stop the recursion after finding the target ?
  2. Return the path list exactly at the specified point ?
result = []

def dfs(graph, vertex, visited, path):

    global result
    if vertex not in visited:
        visited.add(vertex)
        if isTarget(vertex):
            print("Solution found ! " + str(path))
            result = path.copy() # recursion must stop here and return path at this state
        for neighbor in graph.getSuccessors(vertex):
            path.append(neighbor[1]) #neighbor[1] is direction 
            print("Visiting node" + str(neighbor[0]))
            dfs(graph, neighbor[0], visited, path)
            path.pop()

Solution

  • From what I think, dfs() can return a list, which would allow us to continue/break the recursion. Something like:

    result = []
    
    def dfs(graph, vertex, visited, path):
    
        if vertex not in visited:
            visited.add(vertex)
            if isTarget(vertex):
                print("Solution found ! " + str(path))
                return path # recursion stops here and returns path at this state
            for neighbor in graph.getSuccessors(vertex):
                path.append(neighbor[1]) #neighbor[1] is direction 
                print("Visiting node" + str(neighbor[0]))
                temp_path = dfs(graph, neighbor[0], visited, path)
                if temp_path:
                    return temp_path # break recursion since path found
                path.pop()
        return [] # if no path/target node found
    
    result = dfs()