Search code examples
pythonalgorithmrecursiongraphdepth-first-search

How to manipulate and return a string from a recursive function?


I wrote the recursive code to get the path taken in a DFS traversal, but I want to get the output into a string variable. Recursion is not my strong suit so I'm having a lot of trouble figuring out the what to return. Here's the code I wrote for the algorithm

adj_lst = [None, [3, 4], [3], [1, 2], [1]]
size = len(adj_lst)
visited = [False] * size

def dfs(starting_node, a_lst, output):
    visited[starting_node] = True
    output += str(starting_node)

    for vertex in a_lst[starting_node]:

        if visited[vertex] == False:
            visited[vertex] = True
            dfs(vertex, a_lst, output)

    return output


print(dfs(1,adj_lst,''))

I give an adjacency list of an undirected graph where the index corresponds to the parent node and the list inside contains the child nodes. Every time a node gets visited, I add that node to the output variable and return it in the end.

In this case the desired output is "1 3 2 4" but what I get is "1"


Solution

  • adj_lst = [None, [3, 4], [3], [1, 2], [1]]
    size = len(adj_lst)
    visited = [False] * size
    
    def dfs(starting_node, a_lst, output):
        visited[starting_node] = True
        output += str(starting_node)
    
        for vertex in a_lst[starting_node]:
            if visited[vertex] == False:
                visited[vertex] = True
                output = dfs(vertex, a_lst, output)
    
        return output
    
    
    print(dfs(1,adj_lst,''))