Write pseudocode for DFS algorithme and BFS algorithme

QuestionsCategory: QuestionsWrite pseudocode for DFS algorithme and BFS algorithme
tras asked 5 months ago

Write pseudocode for DFS algorithme and BFS algorithme

1 Answers
Techtuna Staff answered 5 months ago

# 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