Implement Breadth-First Search (BFS) Graph Algorithm in Python using Loop

Author: Al-mamun Sarkar Date: 2020-03-29 20:00:57

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

Code:

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

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


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