15,944,733 members
See more:
I wrote this code to find a path between two nodes (using dfs algorithm) , and there is an error in it could you please help me

What I have tried:

```graph = {

'S':['D', 'A', 'B' ],

'A':['C' ],

'B' :['D'],

'C' :['G', 'D' ],

'D':['G'] }

def dfs ( graph , start , goal ) :

visited = [ ]

stack = [ [ start ] ]

while stack :

path = stack.pop()

node = path [ -1 ]

if node in visited :

continue

visited.append ( node )

if node == goal :

return path

else :

adjacent_nodes = graph.get ( node , [ ])

for node2 in adjacent_nodes :

if node2 not in path :

new_path = list ( path)

new_path.append ( node2 )

stack.append ( new_path )

Solution = dfs(graph, 'S', 'G')

Print ( 'solution is :', Solution)```
Posted
Richard MacCutchan 28-Dec-22 4:45am
"there is an error in it"
What error and where does it occur?
Somia098 29-Dec-22 21:28pm
I couldn't know where I'm beginner in python and i want to write Depth first search program to find a path from source to target but i couldn't

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Pete O'Hanlon 60 aisha.offical 20 Greg Utas 10 OriginalGriff 10 Stephen Hewison 5
 Pete O'Hanlon 965 OriginalGriff 810 Richard Deeming 715 merano99 345 Dave Kreskowiak 310

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900