# A DFS function

def DFS(self, v, visited):

# Mark the current node as visited and print

visited[v] = True

print(v, end = ‘ ‘)

# do same for all the vertices

# and adjacent to that vertex

for i in self.graph[v]:

if visited[i] == False:

self.DFS(i, visited)

# function for DFS traversal.

# by recursive DFSU()

def DFS(self, v):

# Mark all the vertices as not visited

visited = [False] * (len(self.graph))

# Call the recursive function

# to print DFS traversal

self.DFSU(v, visited)

# A BFS function

def BFS(self, s):

# Mark all the vertices as not visited

visited = [False] * (len(self.graph))

# Create a queue for BFS

queue = []

# Mark the source node as

# visited and enqueue it

queue.append(s)

visited[s] = True

while queue:

# Dequeue a vertex from

s = queue.pop(0)

print (s, end = ” “)

# get all adjacent dequed vertwx and after visiting enqueue and mark visited

for i in self.graph[s]:

if visited[i] == False:

queue.append(i)

visited[i] = True

Please login or Register to submit your answer