Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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' : ['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'] 

visited = [] 

def dfs(graph,node): 

global visited 

if node not in visited:

visited.append(node) 

for n in graph[node]: 

dfs(graph,n) 

dfs(graph1,'A') 

print(visited)

Output:

['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']

1 Answer

0 votes
by (106k points)

You should use the below-mentioned code:-

graph1 = { 

'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'] 

def dfs(graph, node, visited):

if node not in visited:

visited.append(node) 

for n in graph[node]:

dfs(graph,n, visited)

return visited 

visited = dfs(graph1,'A', []) 

print(visited)

Browse Categories

...