Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views1 page

Depth First Search

Uploaded by

mysticpatel20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views1 page

Depth First Search

Uploaded by

mysticpatel20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

from collections import defaultdict

class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addEdge(self,u,v,c):
self.graph[u].append((v,c))
self.graph[v].append((u,c))
def dispg(self):
print(self.graph.items())
def DFS(self,s,goal):
visited=[False]*(len(self.graph))
frontier=[]
frontier.append(s)
visited[s]=True
while frontier:
s=frontier.pop()
print(s,end=" ")
if(s==goal):
print("Goal Found!")
return 1
for i,j in self.graph[s]:
if visited[i]==False:
frontier.append(i)
visited[i]=True
g = Graph()
g.addEdge(0, 1,9)
g.addEdge(0, 2,5)
g.addEdge(1, 2,8)
g.addEdge(2, 3,2)
g.addEdge(3, 4,4)
g.addEdge(3, 0,1)
g.addEdge(4, 0,4)
g.dispg()
print ("\n Following is Depth First Traversal (starting from vertex 1)")
g.DFS(1,4)

You might also like