Sunday, January 12, 2025
HomeComputer ScienceBreadth First Search or BFS for a Graph

Breadth First Search or BFS for a Graph

Breadth-First Search (BFS) is a graph traversal algorithm used to explore nodes and edges in a graph systematically. It starts from a given source node and explores all its neighbors before moving on to their neighbors, ensuring the search progresses level by level.

Key Characteristics of BFS

  1. Level-order traversal: Visits nodes layer by layer (or distance by distance) from the source.
  2. Uses a queue: It relies on the FIFO (First In, First Out) principle for node exploration.
  3. Time complexity: O(V+E)O(V + E), where VV is the number of vertices and EE is the number of edges.
  4. Space complexity: O(V)O(V), for the visited list and queue.
  5. Applicable for:
    • Finding the shortest path in an unweighted graph.
    • Checking graph connectivity.
    • Solving puzzles and problems like maze traversal.
See also  Bitwise Operator in Java

BFS Algorithm

  1. Start with the source node.
  2. Mark the source node as visited.
  3. Add the source node to a queue.
  4. While the queue is not empty:
    • Remove the front node from the queue.
    • Visit all its unvisited neighbors, mark them as visited, and add them to the queue.

Python Implementation

python
from collections import deque

def bfs(graph, start):
visited = set() # To track visited nodes
queue = deque([start]) # Initialize queue with the start node
result = [] # To store the order of traversal

while queue:
node = queue.popleft() # Dequeue the front node
if node not in visited:
visited.add(node) # Mark the node as visited
result.append(node) # Append the node to the result
# Add unvisited neighbors to the queue
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)

return result

# Example graph (Adjacency List)
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}

# Perform BFS
start_node = 'A'
print("BFS Traversal:", bfs(graph, start_node))

Output for the Example

Given the graph above, the BFS traversal starting from 'A' is:

less
BFS Traversal: ['A', 'B', 'C', 'D', 'E', 'F']

Explanation

  1. Start at 'A', visit its neighbors 'B' and 'C'.
  2. Move to 'B', visit its neighbors 'D' and 'E'.
  3. Move to 'C', visit its neighbor 'F'.
  4. Continue until all nodes are visited.

Advantages

  • Guarantees the shortest path in an unweighted graph.
  • Simple and easy to implement.

Disadvantages

  • Requires extra memory for the queue.
  • May become slow for dense or large graphs.

BFS is foundational for solving many graph-based problems, such as finding connected components, detecting cycles, and pathfinding in games.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x