Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
261 views
in Information Technology by (178k points)
Explore the power of BFS algorithm – a fundamental technique in computer science. Learn the ins and outs of Breadth-First Search, its applications, and implementation. Master graph traversal, shortest path finding, and optimize your problem-solving skills. Dive into the world of BFS with our comprehensive guide.

Please log in or register to answer this question.

2 Answers

0 votes
by (178k points)

Breadth-First Search (BFS) Algorithm

Breadth-First Search (BFS) is a graph traversal algorithm that explores all the vertices at the current depth prior to moving on to vertices at the next depth level. It is often used for finding the shortest path in an unweighted graph.

1. Initialization:

  • Start with a queue data structure and mark all vertices as not visited.

2. Choose a Starting Vertex:

  • Select a starting vertex and enqueue it into the queue.
  • Mark the chosen vertex as visited.

3. Explore Neighbors:

  • Dequeue a vertex from the queue and explore its neighbors.
  • Enqueue any unvisited neighbors and mark them as visited.
  • Repeat this process until the queue is empty.

4. Continue Exploration:

  • If there are remaining unvisited vertices, choose one as the new starting point and repeat steps 2 and 3.

5. Termination:

  • The algorithm terminates when all vertices are visited or when a specific condition is met.

Applications of BFS Algorithm:

  1. Shortest Path in Unweighted Graphs:

    • BFS can be used to find the shortest path between two vertices in an unweighted graph.
  2. Connected Components:

    • BFS can identify connected components in an undirected graph.
  3. Web Crawling:

    • BFS is used in web crawlers to discover and index web pages.
  4. Network Broadcasting:

    • BFS helps in broadcasting information in a network, ensuring all nodes receive the message.
  5. Maze Solving:

    • BFS can be applied to find the shortest path through a maze.

Example of BFS Algorithm:

Consider the following undirected graph:

      1
     / \
    2 - 3
   / \
  4 - 5
 

Starting from vertex 1, the BFS traversal would be: 1 -> 2 -> 3 -> 4 -> 5

Complexity of BFS Algorithm:

  • Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
  • Space Complexity: O(V), where V is the number of vertices.

Implementation of BFS Algorithm (Python):

Here's a simple example of BFS implemented in Python:

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)

    while queue:
        vertex = queue.popleft()
        print(vertex, end=' ')

        for neighbor in graph[vertex]:
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)

# Example Usage:
graph = {
    1: [2, 3],
    2: [1, 4, 5],
    3: [1],
    4: [2],
    5: [2]
}

print("BFS Traversal:")
bfs(graph, 1)
 

This code performs a BFS traversal starting from vertex 1 in the provided graph. The graph dictionary represents the adjacency list of the graph.

0 votes
by (178k points)

FAQs on BFS algorithm

Q: What is BFS?

A: BFS (Breadth-First Search) is an algorithm used to traverse or search tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph) and explores the neighbor nodes at the present depth prior to moving on to nodes at the next depth level.

Q: How does BFS work?

A: BFS works by visiting nodes level by level. It starts at the root node and explores all the neighbor nodes at the current depth before moving on to nodes at the next depth level.

Q: What is the time complexity of BFS?

A: The time complexity of BFS is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Q: How is BFS implemented?

A: BFS can be implemented using a queue data structure. The algorithm involves visiting a node, enqueueing its neighbors, and then dequeuing the node. This process continues until all reachable nodes are visited.

Q: What is the space complexity of BFS?

A: The space complexity of BFS is O(V), where V is the number of vertices. This is because the algorithm uses a queue to store nodes.

Example Code in Python:

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])

    while queue:
        node = queue.popleft()
        if node not in visited:
            print(node, end=' ')
            visited.add(node)
            queue.extend(neighbor for neighbor in graph[node] if neighbor not in visited)

# Example Graph
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F', 'G'],
    'D': ['B'],
    'E': ['B', 'H'],
    'F': ['C'],
    'G': ['C'],
    'H': ['E']
}

# Starting node
start_node = 'A'

print("BFS starting from node", start_node)
bfs(graph, start_node)
 

In this example, the graph represents a simple undirected graph, and the bfs function performs BFS traversal starting from a specified node (start_node). The result is printed in the order nodes are visited.

Important Interview Questions and Answers on BFS algorithm

Q: What is BFS?

Breadth-First Search (BFS) is a graph traversal algorithm that explores all the vertices of a graph level by level. It starts from a source vertex and explores its neighbors before moving on to the next level of vertices.

Q: Explain the basic idea behind BFS.

BFS uses a queue data structure to keep track of the vertices to be explored. It starts with the source vertex, explores its neighbors, enqueues them, and then dequeues the source vertex. This process continues until all vertices are visited.

Q: How does BFS work on a graph?

BFS starts by enqueueing the source vertex. Then, it dequeues a vertex, explores its neighbors, and enqueues them if they haven't been visited. This process continues until the queue is empty, ensuring that vertices are visited in a level-wise manner.

Q: What is the time complexity of BFS?

The time complexity of BFS is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Q: Write a Python code for BFS.

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    
    while queue:
        vertex = queue.popleft()
        if vertex not in visited:
            print(vertex, end=' ')
            visited.add(vertex)
            queue.extend(neighbor for neighbor in graph[vertex] if neighbor not in visited)

# Example Usage:
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F', 'G'],
    'D': ['B'],
    'E': ['B', 'H'],
    'F': ['C'],
    'G': ['C'],
    'H': ['E']
}

print("BFS starting from vertex 'A':")
bfs(graph, 'A')
 

Q: What is the purpose of the 'visited' set in BFS?

The 'visited' set is used to keep track of vertices that have already been explored to avoid revisiting them and to prevent an infinite loop in case of cyclic graphs.

Q: Can BFS be used to find the shortest path in an unweighted graph?

Yes, BFS can be used to find the shortest path in an unweighted graph because it explores vertices level by level, and the first occurrence of a vertex is the shortest path to that vertex.

Q: Explain how BFS can be modified to find the shortest path in a weighted graph.

To find the shortest path in a weighted graph, you can use Dijkstra's algorithm, as BFS does not consider edge weights. Dijkstra's algorithm assigns a distance to each vertex and updates the distances based on the edge weights during traversal.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...