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's an iterative (non-recursive) implementation of a DFS:
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])) # add vertex in the same order as visited
return traversal
test_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']
}
print(dfs_iterative(test_graph, 'A'))
Output:
['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']