Can you please let me know what is incorrect in below DFS code. It\'s giving correct result AFAIK, but I don\'t know when it will fail.
graph1 = {
\'A\'
Here is a more versatile algorithm, the one asked in the question works only for undirected graphs. But this hopefully works for both them. Check it out
graph1= {
'A' : ['B','S'],
'B' : [],
'C' : ['E','S'],
'D' : ['C'],
'E' : ['H'],
'F' : ['C'],
'G' : ['F','S'],
'H' : ['G'],
'S' : []
}
visited = []
def dfs_visit(graph, s):
global visited
for v in graph[s]:
if v not in visited:
visited.append(v)
dfs_visit(graph, v)
def dfs(graph):
global visited
for v in [*graph]:
if v not in visited:
visited.append(v)
dfs_visit(graph,v)
dfs(graph1)
print(visited)