Overview
Test Series
Breadth First Search, or BFS, is a method used to explore all the nodes in a graph, step by step. It starts at one node (called the starting or source node) and checks all the nearby or connected nodes first. After visiting those, it moves on to check the neighbors of those nodes, and so on. This continues until there are no more nodes left to visit.
BFS uses a queue, a structure where the first item added is the first one taken out. This helps in making sure the nodes are visited in the right order — level by level.
Maths Notes Free PDFs
Topic | PDF Link |
---|---|
Class 12 Maths Important Topics Free Notes PDF | Download PDF |
Class 10, 11 Mathematics Study Notes | Download PDF |
Most Asked Maths Questions in Exams | Download PDF |
Increasing and Decreasing Function in Maths | Download PDF |
BFS is very helpful when you want to find the shortest path between two points in an unweighted graph (where all edges are the same cost). It can also be used to check if a graph has any loops or cycles.
In this mathematics article, we will cover the various aspects of the Breadth First Search (BFS) algorithm such as its purpose, how it works, and its advantages. By the end of the article, the reader should have a clear idea of the underlying concepts and the mechanics of the BFS algorithm.
Breadth-First Search (BFS) is a method used to explore or search through a graph or a tree. It starts from a selected node, often called the starting or root node, and looks at all its nearby (adjacent) nodes first. After checking those, it moves on to explore the next level of nodes — the neighbors of the already visited ones — and continues this process level by level.
BFS uses a step-by-step approach, making sure it visits all nodes that are closer before moving on to those that are farther away. It uses a queue to keep track of which nodes to visit next and makes sure it doesn’t visit the same node more than once by keeping a list of visited nodes.
This method is widely used because it helps find the shortest path in unweighted graphs and is a good way to explore every part of a graph, starting from any node.
To learn about the faces, edges and vertices for different shapes with examples.
Breadth First Search (BFS) is a graph traversal algorithm that explores all the vertices of a graph in a breadthward motion, starting from a given source vertex. It uses a queue data structure to keep track of the vertices that are yet to be explored. The algorithm works as follows:
Step 1: Begin by choosing a graph that you want to navigate.
Step 2: Select a starting vertex from which you want to traverse the graph.
Step 3: Choose two data structures to use for traversing the graph: a visited array of size equal to the number of vertices in the graph, and a queue data structure.
Step 4: Start with the chosen vertex and add it to the visited array. Enqueue all adjacent vertices of the starting vertex into the queue.
Step 5: Remove the first vertex from the queue using the FIFO (first-in-first-out) concept, add it to the visited array, and enqueue all of its unvisited adjacent vertices into the queue.
Step 6: Repeat step 5 until the queue is empty and there are no unvisited vertices left in the graph.
Let us understand the algorithm of breadth first search with the help of an example. Consider that we will begin the traversal of the following graph from vertex 2.
To learn about the adjacency matrix, how to create an adjacency matrix with examples.
BFS is a graph traversal algorithm that explores the graph layer by layer, starting at a given source vertex. The algorithm explores all the vertices at a particular distance from the source vertex before moving on to vertices at the next distance.
Pseudocode of implement the BFS traversal on Graph:
Breadth_First_Search( Graph, X ) / Here, Graph is the graph that we already have and X is the source node
Let Q be the queue
Q.enqueue( X ) / Inserting source node X into the queue
Mark X node as visited.
While ( Q is not empty )
Y = Q.dequeue( ) / Removing the front node from the queue
Process all the neighbors of Y, For all the neighbors Z of Y
If Z is not visited, Q. enqueue( Z ) / Stores Z in Q
Mark Z as visited
You can implement the BFS traversal by following the method described below:
Illustration:
Step 1: Initially the queue and visited arrays are empty.
Step 2: Push node 0 into the queue and mark it visited.
Step 3: Remove node 0 from the front of the queue and visit the unvisited neighbours and push them into the queue.
Step 4: Remove node 1 from the front of the queue and visit the unvisited neighbours and push them into the queue.
Step 5: Remove node 2 from the front of the queue and visit the unvisited neighbours and push them into the queue.
Step 6: Remove node 3 from the front of the queue and visit the unvisited neighbours and push them into the queue.
As we can see that every neighbour of node 3 is visited, so move to the next node that is in the front of the queue.
Step 7: Remove node 4 from the front of the queue and visit the unvisited neighbours and push them into the queue.
As we can see that every neighbour of node 4 is visited, so move to the next node that is in the front of the queue.
Now, the queue becomes empty, So, terminate these process of iteration.
This implementation of the BFS traversal algorithm utilizes the adjacency list representation of graphs. To store the lists of adjacent nodes and the queue of nodes required for BFS traversal, the list container of the STL (Standard Template Library) is used.
Here is a Python implementation of the BFS (Breadth-First Search) traversal algorithm for a graph:
# Python3 Program to print BFS traversal from a given source vertex. BFS(int s) traverses
# vertices reachable from s.
from collections import defaultdict
# This class represents a directed graph using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (max(self.graph) + 1)
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print(s, end=" ")
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print(“Following is Breadth First Traversal (starting from vertex 2)”)
g.BFS(2)
Output of the program:
Following is Breadth First Traversal (starting from vertex 2) 2 0 3 1
To learn about the different types of graphs in graph theory, their subgraphs, properties with examples.
Breadth First Search (BFS) is a graph traversal algorithm that visits all the vertices of a graph in breadth-first order, i.e., it visits all the vertices at the same level before moving to the next level.
For a disconnected graph, there may be multiple connected components, i.e., subgraphs that are not connected to each other. To perform BFS on a disconnected graph, we need to apply BFS on each connected component separately.
Here's the algorithm for BFS on a disconnected graph:
To learn about connectivity in graph theory with solved problems.
To implement this algorithm, we can use a queue to store the vertices to be visited, and a boolean array to keep track of visited vertices. Here's the implementation in Python:
from collections import deque
def bfs_disconnected(graph):
n = len(graph) # number of vertices
visited = [False]*n # mark all vertices as not visited
for v in range(n):
if not visited[v]:
queue = deque([v]) # start BFS from v
visited[v] = True
while queue:
u = queue.popleft()
print(u, end=' ')
for neighbor in graph[u]:
if not visited[neighbor]:
queue.append(neighbor)
visited[neighbor] = True
print()
Breadth-first search (BFS) is a popular algorithm used to traverse and search graphs and tree structures. When applied to a tree, it starts at the root node and explores all the neighboring nodes at the current level before moving on to the next level.
The BFS algorithm can be used to construct a breadth-first search tree (BFST), which is a tree that represents the order in which nodes are visited during the BFS traversal of a graph or tree.
To construct a BFS tree, we start by initializing a queue with the root node of the tree. Then, we repeatedly dequeue the front node of the queue, visit its neighbors, and add them to the queue if they have not been visited before. As we visit each node, we add it to the BFST as a child of its parent node.
The resulting tree has the same number of nodes as the original tree, but the edges are directed from parents to children, reflecting the order in which nodes are visited during the BFS traversal.
BFS trees can be useful in a variety of applications, such as network routing, shortest path algorithms, and graph visualization.
The time complexity of Breadth First Search (BFS) algorithm is O(V+E), where V is the number of vertices and E is the number of edges in the graph.
In BFS, we traverse the graph level by level starting from a given source vertex. We first visit all the vertices at distance 1 from the source, then all vertices at distance 2, and so on until we have visited all vertices reachable from the source vertex.
The algorithm visits each vertex and each edge only once. Therefore, the time complexity of BFS is proportional to the sum of the number of vertices and edges in the graph, which is O(V+E).
The space complexity of BFS is O(V) because it uses an array of size V to store the BFS traversal. We also used an array of size V to keep track of visited vertices. We used a queue of size V to store the vertices.
In Breadth First Search (BFS), several key terms help describe how the algorithm works. These include concepts like graphs (made of nodes and edges), queues for tracking progress, and visited sets to avoid repetition. Understanding these terms is essential to grasp how BFS explores data level by level.
Graph:
A graph is a structure made up of points (called nodes or vertices) and lines (called edges) that connect them. In BFS, this graph can go in one direction (directed) or both (undirected).
Node (Vertex):
These are the individual points in a graph. BFS starts from one node and explores other connected nodes from there.
Edge:
An edge is the line or link between two nodes. It shows which nodes are directly connected in the graph.
Queue:
This is a type of list where the first item added is the first one removed (First-In-First-Out or FIFO). BFS uses a queue to keep track of the next node to explore.
Visited Set:
To avoid checking the same node again and again, BFS keeps a list or set of nodes it has already visited.
Root or Starting Node:
This is where the BFS begins. From this node, the search spreads out to other connected nodes.
Level or Layer:
This tells how far a node is from the starting node. BFS explores all nodes one step away first, then moves to nodes two steps away, and so on.
Breadth First Search (BFS) is a powerful algorithm that can be used in various applications, some of which are:
To learn about the distance between points, their formula and derivation with examples.
Breadth First Search (BFS) and Depth First Search (DFS) are two popular algorithms used for traversing or searching in a graph or tree data structure.
BFS visits all the vertices at a given level before moving to the next level, while DFS visits all the vertices along a path from the starting vertex as far as possible before backtracking. Here are some of the key differences between BFS and DFS.
Parameter |
Breadth First Search |
Depth First Search |
Search Order |
BFS visits vertices in the order of their distance from the source vertex. |
DFS visits vertices in the order of their depth from the source vertex. |
Memory Usage |
BFS uses a queue to store the vertices, and hence requires more memory than DFS. |
DFS uses a stack (or recursion) to store the vertices, and hence uses less memory than BFS. |
Completeness |
BFS is guaranteed to find the shortest path between the source and any other vertex in an unweighted graph. |
DFS may not find the shortest path, and may get stuck in an infinite loop if the graph has cycles. |
Time Complexity |
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. |
Time complexity of DFS is O(V+E), where V is the number of vertices and E is the number of edges in the graph. |
In summary, BFS is a good choice when the shortest path is needed, while DFS is useful when memory usage is a concern or when finding any path between two vertices is sufficient.
1.When is breadth first search optimal?
Solution:
Breadth First Search (BFS) is optimal when we want to find the shortest path between two nodes in an unweighted graph or a graph with the same weight on all edges.
BFS explores all the neighbors of a node before moving on to its neighbors' neighbors, and so on. When BFS finds the goal node, it has necessarily explored all the nodes that are at the same or shorter distance from the starting node. This guarantees that the path found by BFS is always the shortest path in terms of the number of edges between the start and goal nodes.
For example, if the neighbors of a node are not sorted, BFS might visit them in different orders each time, leading to different traversal outputs.
Therefore, BFS is only unique if:
In directed graphs, the BFS result can vary even more depending on the direction of edges and the chosen starting node.
We hope that the above article is helpful for your understanding and exam preparations. Stay tuned to the Testbook App for more updates on related topics from Mathematics, and various such subjects. Also, reach out to the test series available to examine your knowledge regarding several exams.
Download the Testbook APP & Get Pass Pro Max FREE for 7 Days
Download the testbook app and unlock advanced analytics.