Breadth First Search or BFS for a Graph17 Mar 2025 | 4 min read What is a Graph?The graph is a data structure where we store the values in terms of nodes or vertices. Nodes are connected to each other via edges, where edges can be weighted or unweighted. If there is an edge between two nodes and it contains some weight then we call it a weighted graph. Otherwise, it is called an unweighted graph. An unweighted graph is a type of graph with no edge weight. In this type of graph, the edges represent the connection between two nodes. If there is an edge between nodes u and v in an unweighted graph then u and v are adjacent to each other. To traverse the graph, we use two approaches:
In DFS, we go to all the deepest nodes of the starting node using recursion. Here, we are talking about BFS. BFSBFS stands for breadth-first search, where we traverse all the neighboring nodes of the source node, and we solve it successively for the adjacent nodes. Traversal of nodes is done radially in BFS. For example: ![]() Next iteration- ![]() Next iteration- ![]() Next iteration- ![]() In the above example, the order of BFS will be: 0->1,2->3,4->5,6 We will use the queue data structure to get the BFS traversal of a graph. Java code:Output: ![]() Explanation In the above example, we have a connected graph in the form of an adjacency list, where each node has the ArrayList of its neighbor nodes. Now to implement the BFS traversal, we use a queue data structure which is initially empty, and also we use a visited array of type Boolean to make sure we don't include that node which has already been covered in the breadth-first search traversal. Initially, we marked the source node as visited and added it into the queue. Now, we will iterate the loop until the queue becomes empty. At each time, we will remove the topmost element of the queue, add it to our answer and add its unvisited neighbor into the queue and mark them visited also. At first iteration- The queue has node 0 and we will add it into our answer, and its neighbor nodes 1 and 2 will be added into the queue and marked visited. Now q=1,2 and answer=0. Now we will remove one add into our answer, and its unvisited neighbor is 3. So now q=2,3 and answer =0,1 Now we will remove 2, add it to our answer and its unvisited neighbor is 4. So now q=3,4 and answer = 0,1,2 Now we will remove 3, add it to our answer and its unvisited neighbors are nothing. So now q=4 and answer = 0,1,2,3 Now we will remove 4, add it to our answer and its unvisited neighbors are 5,6. So now q=5,6 and answer = 0,1,2,3,4 Now we will remove 5, add it to our answer and its unvisited neighbor is nothing. So now q=6 and answer = 0,1,2,3,4,5 Now we will remove 6, add it to our answer and its unvisited neighbor is nothing. So now q=empty and answer = 0,1,2,3,4,5,6 Since the queue is empty, we will stop the loop and return from the functions, and we will print the result. Time complexity: O(N+E) where N is the number of nodes and E is the number of edges Space complexity: O(N) -> for visited array O(N) for result +O(N) for queue. If Graph is Not ConnectedIf the graph is not connected then we will have more than one source vertex for the graph. So we will call BFS for each component separately. For example: ![]() Java code: Output: ![]() Time complexity: O(N+E) where N is the number of nodes and E is the number of edges Next TopicFind an element in array such that sum of the left array is equal to the sum of the right array |
Problem Statement: Inverse pair is an even pair of numbers [i,j], where the first element of the array is i < j < nums.length and nums[i] > nums[j] is true. If the input to the programs is two integers n and k, then return the number of...
9 min read
Introduction: In the realm of programming, effective data management is critical for optimal performance and resource utilization. FIFO (First-In-First-Out) and LIFO (Last-In-First-Out) are two main approaches to data organization. The order in which data elements are retrieved and processed is determined by these mechanisms. In this article,...
4 min read
Minesweeper is played on a grid (game board) comprising of cells. Every cell can be in one of three states: unrevealed, revealed, or flagged. A few cells might contain mines, and the objective is to uncover all cells that don't contain mines. On the off chance...
6 min read
Data structures are essential for effectively organizing and manipulating data in the field of computer science. The BK-tree is one of these structures and is a clever way to index and search data using metric spaces. Burkhard and Keller introduced BK-trees in 1973, and since then,...
7 min read
? An unordered collection of key-value pair items is represented by a map data type. Assign the map data type to ports in order to pass map data via transformations. A map element is a key and value pair that corresponds to one object and maps it...
10 min read
Problem Statement Given a string s, you are tasked with determining the count of valid splits. A split is deemed valid if you can divides into two nonempty substrings, s_first and s_second, such that their combination equals s (i.e., s_first + s_second = s), and both substrings...
10 min read
In this article, we are going to convert a binary tree into a linked list, and to do so; we are going to use various functions. After we are finished with the flattening of the same, the left of each node should point to the NULL...
7 min read
Introduction: The linked list is a fundamental data structure used in computer science and programming for many purposes. While they provide for greater dynamic memory allocation flexibility, they can also present difficulties if loops, commonly referred to as cyclic dependencies, are mistakenly included. A linked list's loops...
5 min read
Binary trees, with their simple yet significant styles, have found various applications in the DSA field and are also rapidly growing. They offer a hierarchical representation of the data that supports searching, sorting, and other things. Determining the maximum sum level in a binary tree poses...
6 min read
Introduction In the field of computer science especially in image processing, Boolean matrices has a vital role to play. A Boolean matrix is a matrix in which the elements represent Boolean values only, true and false or represented by 1 and 0. These matrices find many applications...
11 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India