Implement Breadth-First Search (BFS) Graph Algorithm in Python Using Recursion

Implement Breadth-First Search (BFS) Graph Algorithm in Python Using Recursion

Instructor-svgAl-Mamun Sarkar
Mar 29 , 2020

Implement the Breadth-First Search (BFS) Graph Algorithm in Python using Recursion. The following code shows how to implement the Breadth-First Search (BFS) Algorithm in the Python programming language using recursion. 

Code:

class Graph:
    def __init__(self, graph):
        self.visited = []
        self.queue = []
        self.graph = graph

    def bfs(self, node):
        print(node)
        if node not in self.visited:
            self.visited.append(node)
        for neighbour in self.graph[node]:
            if neighbour not in self.visited:
                self.queue.append(neighbour)
                self.visited.append(neighbour)

        if self.queue:
            vertex = self.queue.pop(0)
            self.bfs(vertex)


graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}
g = Graph(graph)
g.bfs('A')

 

Output:

A
B
C
D
E
F

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram