Search code examples
pythonrecursiongraphdepth-first-search

Why is nested function not changing the variable of main function


def findAllPaths(vertices, Alist, source, dest):
    result = []
    path = []
    visited = []

    def find_path(Alist, source, dest, path, visited):
        path.append(source)
        visited.append(source)

        if source == dest:
            result.append(path)
        else:
            for i in Alist[source]:
                if i not in visited:
                    find_path(Alist, i, dest, path, visited)
        visited.pop()
        path.pop()
    find_path(Alist, source, dest, [] ,[])

    return result


INPUT:
    vertices = [1, 2, 3, 4, 5, 6, 7, 8]
    AList = {1: [3, 4], 2: [3], 3: [6], 4: [6, 7], 5: [4, 6], 6: [2], 7: [5]}
    source = 1
    destination = 2
OUTPUT:
    [[], [], []]

I want to get all the paths from a source to destination in graph. The nested function is giving paths but not changing the variable out of it.


Solution

  • I have changed your code a little bit, but the main problem is that you need to use copy when saving path, because if you don't that all other changes of path also change when path is in result, cause it is the same object actually.

    def findAllPaths(vertices, Alist, source, dest):
        result = []
        path = []
        visited = []
    
        def find_path(Alist, source, dest):
            nonlocal result
            path.append(source)
            visited.append(source)
    
            if source == dest:
                result.append(path.copy())
            else:
                for i in Alist[source]:
                    if i not in visited:
                        find_path(Alist, i, dest)
    
            visited.pop()
            path.pop()
    
        find_path(Alist, source, dest)
    
        return result
    
    
    vertices = [1, 2, 3, 4, 5, 6, 7, 8]
    AList = {1: [3, 4], 2: [3], 3: [6], 4: [6, 7], 5: [4, 6], 6: [2], 7: [5]}
    source = 1
    destination = 2
    
    print(findAllPaths(vertices, AList, source, destination))