How to do BFS search in python? write a full explanation
Breadth-First Search (BFS) is a fundamental algorithm used for traversing graphs or trees. It starts from a given node or "root" and explores all the neighboring nodes at the present depth level before moving on to explore the nodes at the next depth level.
BFS can be implemented using a queue data structure to keep track of the nodes to be visited. Here is a step-by-step guide to implementing BFS in Python:
Step 1: Create a Queue
Create a queue to keep track of the nodes to be visited. In Python, you can use the `collections` module's `deque` function to create a queue.
Step 2: Create a Graph
Create a graph as a dictionary where each key represents a node and its corresponding value represents a list of its neighboring nodes.
Step 3: Enqueue the Starting Node
Enqueue the starting node or "root" node to the queue.
Step 4: Dequeue and Explore Neighbors
Dequeue a node from the queue and explore all its neighboring nodes. Mark the node as visited to avoid revisiting it.
Step 5: Enqueue Unvisited Neighbors
Enqueue all unvisited neighboring nodes of the dequeued node.
Step 6: Repeat Steps 4-5
Repeat steps 4-5 until the queue is empty, meaning all nodes have been visited.
Here is a Python implementation of BFS:
```
from collections import deque
def bfs(graph, root):
visited = set()
queue = deque([root])
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
print(node, end=" ")
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
# Example graph
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
bfs(graph, 'A') # Output: A B C D E F
```
In this implementation, we use a `deque` to create a queue and a `set` to keep track of visited nodes. We start by enqueueing the root node and then iterate through the queue, dequeuing nodes and exploring their neighbors. We mark each node as visited to avoid revisiting it.
Sources
- Breadth First Search in Python (with Code) | BFS Algorithmfavtutor.com
- Breadth First Search (BFS) Algorithm in Python • datagydatagy.io
- How to Implement Breadth-First Search (BFS) using …pythonpool.com
- Python Program for Breadth First Search or BFS for a Graphgeeksforgeeks.org
- BFS: Breadth First Search Implementation in Pythonpieriantraining.com
- BFS Graph Algorithm(With code in C, C++, Java and Python)programiz.com
- Graphs in Python - Theory and Implementation - Breadth-First …stackabuse.com
- Python - Implement Breadth-First Search (BFS) for Graph and …dev.to