I have the code below to perform a DFS sort on a directed graph (Topological sort, no cycles)
def dfs_recursive(graph, vertex, path=[]):
path += [vertex]
for neighbor in graph[vertex]:
if neighbor not in path:
path = dfs_recursive(graph, neighbor, path)
return path
Yet every time I run the function with my directed graph it returns a graph with numerous cycles dfs_recursive(graph1, 'Comp Sci')
> ['Comp Sci', 'Structures', 'Algebra', 'COB', 'Digital Design', 'Compilers', 'GPU', 'Networking']
This is ran with the following Directed Graph:
graph1 = {
'Digital Design': ['COB', 'Compilers'],
'Structures': ['Algebra', 'Digital Design'],
'Creative Writing': ['Structures', 'System Admin', 'Databases'],
'Algebra': ['COB'],
'Comp Sci': ['Structures', 'GPU'],
'GPU': ['Networking'],
'Networking': ['Algebra'],
'Databases': ['System Admin'],
'COB': [],
'System Admin': [],
'Compilers': []
}
As shown, when working correctly, the function should return > ['Comp Sci', 'Structures', 'Algebra', 'COB']
as there shouldn't be any additional connections. ('COB' does not have any nodes in my Adjacency List, should only go in one direction)
Am I missing something? Is my Directed Graph incorrect? I'm only referencing the nodes in a single direction yet there are random cycles that I can't explain.