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?