0

I can't seem to figure out how to translate my solutions to work on an Directed graph instead of an Undirected graph.

I currently have two different approaches; Iteration and Recursion.

Iteration:

def dfs_iterative(graph, start_vertex):
    visited = set()
    traversal = []
    stack = [start_vertex]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            traversal.append(vertex)
            stack.extend(reversed(graph[vertex]))   
    return traversal

Recursion:

def dfs_recursive(graph, node, visited):
    if node not in visited:
        visited.append(node)
        for n in graph[node]:
            dfs_recursive(graph,n, visited)
    return visited

When testing these against the graph shown below the output is always Undirected.

graph = {
    'A' : ['B','S'],
    'B' : ['A'],
    'C' : ['D','E','F','S'],
    'D' : ['C'],
    'E' : ['C','H'],
    'F' : ['C','G'],
    'G' : ['F','S'],
    'H' : ['E','G'],
    'S' : ['A','C','G']
}
# returns ['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']

I wanted to first figure out how to change my code so the edges of my graphs are directed in a single direction, and then how to call these functions to get the rest of the different paths within the graph.

If I had to guess some psuedocode for the latter I would assume

Call function with random vertex
    store result in Dict
    repeat while result not in Dict
    Repeat recursively 

Could it be done iteratively?

William Merritt
  • 429
  • 1
  • 5
  • 12
  • 1
    I don't understand the question. What is stopping you from applying your function `dfs_iterative`, without modifying it at all, to a graph which is directed? The `graph` argument of `dfs_iterative` is a list of adjacency lists. The example list of adjacency lists that you show us happens to correspond to an undirected graph (ie, a graph where for every edge a->b, there is a corresponding edge b->a). Try passing the adjacency list of a directed graph to your function, and it should work. – Stef Aug 28 '21 at 23:12
  • Undirected graphs are a type of directed graph. It's just a directed graph where every node `a` that has an edge to node `b` always has an edge from `b` back to `a` as well. So no changes are necessary. I don't really understand the question here either. – ggorlen Aug 29 '21 at 02:16

0 Answers0