Breadth First Search (BFS) for a Graph Algorithm

Let’s discuss the algorithm for the BFS:

  1. Initialization: Enqueue the starting node into a queue and mark it as visited.
  2. Exploration: While the queue is not empty:
    • Dequeue a node from the queue and visit it (e.g., print its value).
    • For each unvisited neighbor of the dequeued node:
      • Enqueue the neighbor into the queue.
      • Mark the neighbor as visited.
  3. Termination: Repeat step 2 until the queue is empty.

This algorithm ensures that all nodes in the graph are visited in a breadth-first manner, starting from the starting node.

Breadth First Search or BFS for a Graph

Breadth First Search (BFS) is a fundamental graph traversal algorithm. It involves visiting all the connected nodes of a graph in a level-by-level manner. In this article, we will look into the concept of BFS and how it can be applied to graphs effectively

Table of Content

  • Breadth First Search or BFS for a Graph
  • Relation between BFS for Graph and BFS for Tree
  • Breadth First Search (BFS) for a Graph Algorithm
  • How Does the BFS Algorithm Work?
  • Implementation of BFS for Graph using Adjacency List
  • Complexity Of Breadth-First Search (BFS) Algorithm
  • Applications of BFS in Graphs
  • Problems on Breadth First Search or BFS for a Graph
  • FAQs on Breadth First Search (BFS) for a Graph

Similar Reads

Breadth First Search (BFS) for a Graph:

Breadth First Search (BFS) is a graph traversal algorithm that explores all the vertices in a graph at the current depth before moving on to the vertices at the next depth level. It starts at a specified vertex and visits all its neighbors before moving on to the next level of neighbors. BFS is commonly used in algorithms for pathfinding, connected components, and shortest path problems in graphs....

Relation between BFS for Graph and BFS for Tree:

Breadth-First Traversal (BFS) for a graph is similar to the Breadth-First Traversal of a tree....

Breadth First Search (BFS) for a Graph Algorithm:

Let’s discuss the algorithm for the BFS:...

How Does the BFS Algorithm Work?

Starting from the root, all the nodes at a particular level are visited first and then the nodes of the next level are traversed till all the nodes are visited....

Implementation of BFS for Graph using Adjacency List:

C++ #include #include #include using namespace std; // Function to perform Breadth First Search on a graph // represented using adjacency list void bfs(vector >& adjList, int startNode, vector& visited) { // Create a queue for BFS queue q; // Mark the current node as visited and enqueue it visited[startNode] = true; q.push(startNode); // Iterate over the queue while (!q.empty()) { // Dequeue a vertex from queue and print it int currentNode = q.front(); q.pop(); cout << currentNode << " "; // Get all adjacent vertices of the dequeued vertex // currentNode If an adjacent has not been visited, // then mark it visited and enqueue it for (int neighbor : adjList[currentNode]) { if (!visited[neighbor]) { visited[neighbor] = true; q.push(neighbor); } } } } // Function to add an edge to the graph void addEdge(vector >& adjList, int u, int v) { adjList[u].push_back(v); } int main() { // Number of vertices in the graph int vertices = 5; // Adjacency list representation of the graph vector > adjList(vertices); // Add edges to the graph addEdge(adjList, 0, 1); addEdge(adjList, 0, 2); addEdge(adjList, 1, 3); addEdge(adjList, 1, 4); addEdge(adjList, 2, 4); // Mark all the vertices as not visited vector visited(vertices, false); // Perform BFS traversal starting from vertex 0 cout << "Breadth First Traversal starting from vertex " "0: "; bfs(adjList, 0, visited); return 0; } C #include #include #define MAX_VERTICES 100 // Structure to represent a node in adjacency list struct Node { int data; struct Node* next; }; // Function to create a new node struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; } // Function to add an edge to the graph void addEdge(struct Node* adjList[], int u, int v) { struct Node* newNode = createNode(v); newNode->next = adjList[u]; adjList[u] = newNode; } // Function to perform Breadth First Search on a graph // represented using adjacency list void bfs(struct Node* adjList[], int vertices, int startNode, int visited[]) { // Create a queue for BFS int queue[MAX_VERTICES]; int front = 0, rear = 0; // Mark the current node as visited and enqueue it visited[startNode] = 1; queue[rear++] = startNode; // Iterate over the queue while (front != rear) { // Dequeue a vertex from queue and print it int currentNode = queue[front++]; printf("%d ", currentNode); // Get all adjacent vertices of the dequeued vertex // currentNode If an adjacent has not been visited, // then mark it visited and enqueue it struct Node* temp = adjList[currentNode]; while (temp != NULL) { int neighbor = temp->data; if (!visited[neighbor]) { visited[neighbor] = 1; queue[rear++] = neighbor; } temp = temp->next; } } } int main() { // Number of vertices in the graph int vertices = 5; // Adjacency list representation of the graph struct Node* adjList[vertices]; for (int i = 0; i < vertices; ++i) adjList[i] = NULL; // Add edges to the graph addEdge(adjList, 0, 1); addEdge(adjList, 0, 2); addEdge(adjList, 1, 3); addEdge(adjList, 1, 4); addEdge(adjList, 2, 4); // Mark all the vertices as not visited int visited[vertices]; for (int i = 0; i < vertices; ++i) visited[i] = 0; // Perform BFS traversal starting from vertex 0 printf( "Breadth First Traversal starting from vertex 0: "); bfs(adjList, vertices, 0, visited); return 0; } Java import java.util.LinkedList; import java.util.Queue; // Class to represent a graph using adjacency list class Graph { int vertices; LinkedList[] adjList; @SuppressWarnings("unchecked") Graph(int vertices) { this.vertices = vertices; adjList = new LinkedList[vertices]; for (int i = 0; i < vertices; ++i) adjList[i] = new LinkedList<>(); } // Function to add an edge to the graph void addEdge(int u, int v) { adjList[u].add(v); } // Function to perform Breadth First Search on a graph // represented using adjacency list void bfs(int startNode) { // Create a queue for BFS Queue queue = new LinkedList<>(); boolean[] visited = new boolean[vertices]; // Mark the current node as visited and enqueue it visited[startNode] = true; queue.add(startNode); // Iterate over the queue while (!queue.isEmpty()) { // Dequeue a vertex from queue and print it int currentNode = queue.poll(); System.out.print(currentNode + " "); // Get all adjacent vertices of the dequeued // vertex currentNode If an adjacent has not // been visited, then mark it visited and // enqueue it for (int neighbor : adjList[currentNode]) { if (!visited[neighbor]) { visited[neighbor] = true; queue.add(neighbor); } } } } } public class Main { public static void main(String[] args) { // Number of vertices in the graph int vertices = 5; // Create a graph Graph graph = new Graph(vertices); // Add edges to the graph graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.addEdge(2, 4); // Perform BFS traversal starting from vertex 0 System.out.print( "Breadth First Traversal starting from vertex 0: "); graph.bfs(0); } } Python3 from collections import deque # Function to perform Breadth First Search on a graph # represented using adjacency list def bfs(adjList, startNode, visited): # Create a queue for BFS q = deque() # Mark the current node as visited and enqueue it visited[startNode] = True q.append(startNode) # Iterate over the queue while q: # Dequeue a vertex from queue and print it currentNode = q.popleft() print(currentNode, end=" ") # Get all adjacent vertices of the dequeued vertex # If an adjacent has not been visited, then mark it visited and enqueue it for neighbor in adjList[currentNode]: if not visited[neighbor]: visited[neighbor] = True q.append(neighbor) # Function to add an edge to the graph def addEdge(adjList, u, v): adjList[u].append(v) def main(): # Number of vertices in the graph vertices = 5 # Adjacency list representation of the graph adjList = [[] for _ in range(vertices)] # Add edges to the graph addEdge(adjList, 0, 1) addEdge(adjList, 0, 2) addEdge(adjList, 1, 3) addEdge(adjList, 1, 4) addEdge(adjList, 2, 4) # Mark all the vertices as not visited visited = [False] * vertices # Perform BFS traversal starting from vertex 0 print("Breadth First Traversal starting from vertex 0:", end=" ") bfs(adjList, 0, visited) if __name__ == "__main__": main() C# using System; using System.Collections.Generic; // Class to represent a graph using adjacency list class Graph { int vertices; List[] adjList; public Graph(int vertices) { this.vertices = vertices; adjList = new List[ vertices ]; for (int i = 0; i < vertices; ++i) adjList[i] = new List(); } // Function to add an edge to the graph public void AddEdge(int u, int v) { adjList[u].Add(v); } // Function to perform Breadth First Search on a graph // represented using adjacency list public void BFS(int startNode) { // Create a queue for BFS Queue queue = new Queue(); bool[] visited = new bool[vertices]; // Mark the current node as visited and enqueue it visited[startNode] = true; queue.Enqueue(startNode); // Iterate over the queue while (queue.Count != 0) { // Dequeue a vertex from queue and print it int currentNode = queue.Dequeue(); Console.Write(currentNode + " "); // Get all adjacent vertices of the dequeued // vertex currentNode If an adjacent has not // been visited, then mark it visited and // enqueue it foreach(int neighbor in adjList[currentNode]) { if (!visited[neighbor]) { visited[neighbor] = true; queue.Enqueue(neighbor); } } } } } class MainClass { public static void Main(string[] args) { // Number of vertices in the graph int vertices = 5; // Create a graph Graph graph = new Graph(vertices); // Add edges to the graph graph.AddEdge(0, 1); graph.AddEdge(0, 2); graph.AddEdge(1, 3); graph.AddEdge(1, 4); graph.AddEdge(2, 4); // Perform BFS traversal starting from vertex 0 Console.Write( "Breadth First Traversal starting from vertex 0: "); graph.BFS(0); } } Javascript // Class to represent a graph using adjacency list class Graph { constructor() { this.adjList = {}; } // Function to add an edge to the graph addEdge(u, v) { if (!this.adjList[u]) this.adjList[u] = []; this.adjList[u].push(v); } // Function to perform Breadth First Search on a graph represented using adjacency list bfs(startNode) { // Create a queue for BFS const queue = []; const visited = new Array(Object.keys(this.adjList).length).fill(false); // Mark the current node as visited and enqueue it visited[startNode] = true; queue.push(startNode); // Iterate over the queue while (queue.length !== 0) { // Dequeue a vertex from queue and print it const currentNode = queue.shift(); console.log(currentNode + " "); // Get all adjacent vertices of the dequeued vertex currentNode // If an adjacent has not been visited, then mark it visited and enqueue it for (const neighbor of this.adjList[currentNode] || []) { if (!visited[neighbor]) { visited[neighbor] = true; queue.push(neighbor); } } } } } // Create a graph const graph = new Graph(); // Add edges to the graph graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.addEdge(2, 4); // Perform BFS traversal starting from vertex 0 console.log("Breadth First Traversal starting from vertex 0: "); graph.bfs(0);...

Complexity Analysis of Breadth-First Search (BFS) Algorithm:

Time Complexity of BFS Algorithm: O(V + E)...

Applications of BFS in Graphs:

BFS has various applications in graph theory and computer science, including:...

Problems on Breadth First Search or BFS for a Graph:

S.noProblems Practice1.Find the level of a given node in an Undirected GraphLink2.Minimize maximum adjacent difference in a path from top-left to bottom-rightLink3.Minimum jump to the same value or adjacent to reach the end of an ArrayLink4.Maximum coin in minimum time by skipping K obstacles along the path in MatrixLink5.Check if all nodes of the Undirected Graph can be visited from the given NodeLink6.Minimum time to visit all nodes of a given Graph at least onceLink7.Minimize moves to the next greater element to reach the end of the ArrayLink8.Shortest path by removing K wallsLink9.Minimum time required to infect all the nodes of the Binary treeLink10.Check if destination of given Matrix is reachable with required values of cellsLink...

FAQs on Breadth First Search (BFS) for a Graph:

Question 1: What is BFS and how does it work?...

Contact Us