bfs Algorithm
The Breadth-First Search (BFS) Queue Algorithm is a widely used graph traversal technique that explores all the vertices of a graph in breadth-first order, meaning it visits all the nodes at the current level before moving on to the nodes at the next level. This algorithm is particularly useful for finding the shortest path in unweighted graphs or for discovering all connected components in a graph. It uses a queue data structure to maintain the order in which nodes are visited and ensures that each node is visited only once.
To implement the BFS algorithm, we start by visiting the source node and marking it as visited. We then enqueue all its adjacent nodes into the queue. The algorithm then proceeds by dequeuing the first node from the queue, visiting its neighbors, and enqueuing any unvisited neighbors. This process continues until the queue is empty, indicating that all reachable nodes have been visited. The BFS algorithm guarantees that every node reachable from the source node will be visited, and the order of visitation will be in increasing distance from the source node. This property of the BFS algorithm makes it a popular choice for various graph-related problems, such as determining the shortest path in unweighted graphs, finding connected components, or solving puzzles that can be modeled as a graph.
"""
BFS.
pseudo-code:
BFS(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
let Q = queue data structure, initialized with s
while Q is non-empty:
remove the first node of Q, call it v
for each edge(v, w): // for w in graph[v]
if w unexplored:
mark w as explored
add w to Q (at the end)
"""
G = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
def bfs(graph, start):
"""
>>> ''.join(sorted(bfs(G, 'A')))
'ABCDEF'
"""
explored, queue = set(), [start] # collections.deque([start])
explored.add(start)
while queue:
v = queue.pop(0) # queue.popleft()
for w in graph[v]:
if w not in explored:
explored.add(w)
queue.append(w)
return explored
if __name__ == "__main__":
print(bfs(G, "A"))