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\'
Without recursion:
def dfs(graph, node):
visited = [node]
stack = [node]
while stack:
node = stack[-1]
if node not in visited:
visited.extend(node)
remove_from_stack = True
for next in graph[node]:
if next not in visited:
stack.extend(next)
remove_from_stack = False
break
if remove_from_stack:
stack.pop()
return visited
print (dfs(graph1, 'A'))
Output:
['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']