Breadth-First Search (BFS) in Graph

Welcome to our beginner's guide to Breadth-First Search (BFS) in Graph Theory! Graph theory is a fascinating branch of mathematics and computer science that deals with the study of graphs, which are mathematical structures used to model pairwise relations between objects.

What is Breadth-First Search (BFS)?

Breadth-First Search is an algorithm used to traverse or search through the nodes of a graph in a systematic manner. It starts at a specific node (often referred to as the "source" node) and explores all the neighboring nodes at the present depth level before moving on to the nodes at the next depth level.

Imagine you're exploring a maze. BFS would systematically explore all the paths starting from your current location before moving on to the paths further away.

How does BFS Work?

BFS employs a simple strategy of exploring nodes level by level. It utilizes a data structure called a queue to keep track of the nodes that need to be visited. The algorithm proceeds as follows:

  1. Start with the source node and enqueue it into the queue.
  2. Mark the source node as visited.
  3. While the queue is not empty:
    • Dequeue a node from the front of the queue.
    • Visit the dequeued node.
    • Enqueue all unvisited neighboring nodes of the dequeued node.
    • Mark each neighboring node as visited.
  4. Repeat steps 3-4 until the queue is empty.

Example of BFS with Visited Tracking

Let's explore Breadth-First Search (BFS) using a simple graph:


       A
      / \
     B - C
    / \   \
   D - E - F

In this graph:

  • A is connected to B and C.
  • B is connected to A, D, and E.
  • C is connected to A and F.
  • D is connected to B and E.
  • E is connected to B, D, and F.
  • F is connected to C and E.

We will perform a BFS traversal starting from node A.

Step-by-Step Traversal:

  1. Begin at Node A (Source):
    • Enqueue A into the queue.
    • Mark A as visited.
    • Queue: [A], Visited: [A]
  2. Visit A, enqueue its unvisited neighbors B and C.
  3. Dequeue A. Queue: [B, C], Visited: [A]
  4. 
           A        --> Level 0
          / \
         B - C      --> Level 1
        / \   \
       D - E - F    --> Level 2
    
  5. Visit B, enqueue its unvisited neighbors D and E.
  6. Dequeue B. Queue: [C, D, E], Visited: [A, B]
  7. 
           A 
          / \
         B - C 
        / \   \
       D - E - F
    
  8. Visit C, enqueue its unvisited neighbor F.
  9. Dequeue C. Queue: [D, E, F], Visited: [A, B, C]
  10. 
           A
          / \
         B - C
        / \   \
       D - E - F
    
  11. Visit D. No new neighbors to enqueue.
  12. Dequeue D. Queue: [E, F], Visited: [A, B, C, D]
  13. 
           A
          / \
         B - C
        / \   \
       D - E - F
    
  14. Visit E. No new neighbors to enqueue.
  15. Dequeue E. Queue: [F], Visited: [A, B, C, D, E]
  16. 
           A
          / \
         B - C
        / \   \
       D - E - F
    
  17. Visit F. No new neighbors to enqueue.
  18. Dequeue F. Queue is now empty, indicating the end of the traversal.
  19. 
           A
          / \
         B - C
        / \   \
       D - E - F
    

Output Result: Nodes visited in BFS order: A, B, C, D, E, F

Time Complexity:

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.

Space Complexity:

The space complexity of BFS, in the worst-case scenario, is O(V), where V is the number of vertices.

This example clearly demonstrates the BFS algorithm's level-by-level traversal through a graph, visiting all reachable nodes systematically.

Implementing BFS Code

Now, let's take a look at how we can implement Breadth-First Search in code. We'll provide examples in several programming languages to help you get started:


package codeKatha;

import java.util.*;

public class BFS {
    public void breadthFirstSearch(Graph graph, Node source) {
    
        Queue<Node> queue = new LinkedList<>();
        Set<Node> visited = new HashSet<>();

        queue.add(source);
        visited.add(source);

        while (!queue.isEmpty()) {
        
            Node current = queue.poll();
            System.out.println(current);

            for (Node neighbor : graph.getNeighbors(current)) {
            
                if (!visited.contains(neighbor)) {
                
                    visited.add(neighbor);
                    queue.add(neighbor);
                    
                }
            }
        }
    }
}

#include <iostream>
#include <queue>
#include <unordered_set>
#include "Graph.h"

void BFS(Graph& graph, Node& source) {
    std::queue<Node> queue;
    std::unordered_set<Node> visited;

    queue.push(source);
    visited.insert(source);

    while (!queue.empty()) {
        Node current = queue.front();
        queue.pop();
        std::cout << current << std::endl;

        for (Node neighbor : graph.getNeighbors(current)) {
            if (visited.find(neighbor) == visited.end()) {
                visited.insert(neighbor);
                queue.push(neighbor);
            }
        }
    }
}

class BFS:
    def breadth_first_search(self, graph, source):
        queue = []
        visited = set()

        queue.append(source)
        visited.add(source)

        while queue:
            current = queue.pop(0)
            print(current)

            for neighbor in graph.get_neighbors(current):
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append(neighbor)

class BFS {
    breadthFirstSearch(graph, source) {
        let queue = [];
        let visited = new Set();

        queue.push(source);
        visited.add(source);

        while (queue.length > 0) {
            let current = queue.shift();
            console.log(current);

            for (let neighbor of graph.getNeighbors(current)) {
                if (!visited.has(neighbor)) {
                    visited.add(neighbor);
                    queue.push(neighbor);
                }
            }
        }
    }
}

Graph: Concept and Important Algorithms

1. Basics of Graph Data Structure
2. Breadth-First Search (BFS) in Graph
3. Depth-First Search (DFS) in Graph 
4. Topological Sort in Graph
5. Union-Find Algorithm in Graph
6. Prim's Algorithm in Graph 
7. Dijkstra's Algorithm in Graph
8. Kruskal's Algorithm in Graph

Congratulations! You've now learned the basics of Breadth-First Search in graph theory. Feel free to experiment with the provided code examples and explore further applications of BFS in your projects.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Visual Studio Code setup for Java and Spring with GitHub Copilot

Java interview questions - Must to know concepts

Spring Data JPA

Data Structures & Algorithms Tutorial with Coding Interview Questions

Elasticsearch Java Spring Boot

Java interview questions for 5 years experience