xxxxxxxxxx
"""
breadFirstSearch method traverses a tree using
the Breadth-first search approach storing
its node values in an array and then
returns the resulting array.
"""
class Node:
def __init__(self, value):
self.value = value
self.children = []
def breadFirstSearch(self, array):
queue = [self]
while len(queue) > 0:
current = queue.pop(0)
array.append(current.value)
for child in current.children:
queue.append(child)
return array
xxxxxxxxxx
def bfs(node):
""" graph breadth-first search - iterative """
from collections import deque
q = deque()
q.append(node)
node.visited = True
while q:
current = d.popleft()
print(current)
for node in current.adjList:
if not node.visited:
q.append(node)
node.visited = True
xxxxxxxxxx
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
print(vertex) # You can modify this line to process the vertex
if vertex not in visited:
visited.add(vertex)
neighbors = graph[vertex]
for neighbor in neighbors:
if neighbor not in visited:
queue.append(neighbor)
# Example usage:
# Define your graph as an adjacency list
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
start_vertex = 'A'
bfs(graph, start_vertex)