Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Comments
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)



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