15,921,577 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
 Richard Deeming 50 Maciej Los 25 Pete O'Hanlon 25 OriginalGriff 25 Dave Kreskowiak 10
 Pete O'Hanlon 995 OriginalGriff 916 Dave Kreskowiak 485 Richard Deeming 340 Richard MacCutchan 320

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