Open In App

Breadth First Search without using Queue

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Breadth-first search is a graph traversal algorithm which traverse a graph or tree level by level. In this article, BFS for a Graph is implemented using Adjacency list without using a Queue.
Examples: 

Input: 

Output: BFS traversal = 2, 0, 3, 1 
Explanation: 
In the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. Therefore, a Breadth-First Traversal of the following graph is 2, 0, 3, 1. 
 

Approach: This problem can be solved using simple breadth-first traversal from a given source. The implementation uses adjacency list representation of graphs
Here: 
 

  • STL Vector container is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal. 
     
  • A DP array is used to store the distance of the nodes from the source. Every time we move from a node to another node, the distance increases by 1. If the distance to reach the nodes becomes smaller than the previous distance, we update the value stored in the DP[node].

Below is the implementation of the above approach:

CPP




// C++ implementation to demonstrate
// the above mentioned approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the distance
// from the source to other nodes
void BFS(int curr, int N, vector<bool>& vis,
         vector<int>& dp, vector<int>& v,
         vector<vector<int> >& adj)
{
 
    while (curr <= N) {
 
        // Current node
        int node = v[curr - 1];
        cout << node << ", ";
 
        for (int i = 0; i < adj[node].size(); i++) {
 
            // Adjacent node
            int next = adj[node][i];
 
            if ((!vis[next])
                && (dp[next] < dp[node] + 1)) {
 
                // Stores the adjacent node
                v.push_back(next);
 
                // Increases the distance
                dp[next] = dp[node] + 1;
 
                // Mark it as visited
                vis[next] = true;
            }
        }
        curr += 1;
    }
}
 
// Function to print the distance
// from source to other nodes
void bfsTraversal(
    vector<vector<int> >& adj,
    int N, int source)
{
    // Initially mark all nodes as false
    vector<bool> vis(N + 1, false);
 
    // Initialize distance array with 0
    vector<int> dp(N + 1, 0), v;
 
    v.push_back(source);
 
    // Initially mark the starting
    // source as 0 and visited as true
    dp = 0;
    vis = true;
 
    // Call the BFS function
    BFS(1, N, vis, dp, v, adj);
}
 
// Driver code
int main()
{
    // No. of nodes in graph
    int N = 4;
 
    // Creating adjacency list
    // for representing graph
    vector<vector<int> > adj(N + 1);
    adj[0].push_back(1);
    adj[0].push_back(2);
    adj[1].push_back(2);
    adj[2].push_back(0);
    adj[2].push_back(3);
    adj[3].push_back(3);
 
    // Following is BFS Traversal
    // starting from vertex 2
    bfsTraversal(adj, N, 2);
 
    return 0;
}


Java




// Java implementation to demonstrate
// the above mentioned approach
 
import java.util.*;
 
public class Main {
    static void bfsTraversal(List<List<Integer>> adj, int N, int source) {
        // Initially mark all nodes as false
        boolean[] vis = new boolean[N + 1];
        Arrays.fill(vis, false);
 
        // Initialize distance array with 0
        int[] dp = new int[N + 1];
        Arrays.fill(dp, 0);
        List<Integer> v = new ArrayList<>();
 
        v.add(source);
 
        // Initially mark the starting
        // source as 0 and visited as true
        dp = 0;
        vis = true;
 
        // Call the BFS function
        bfs(1, N, vis, dp, v, adj);
    }
 
    static void bfs(int curr, int N, boolean[] vis, int[] dp, List<Integer> v, List<List<Integer>> adj) {
        while (curr <= N) {
            // Current node
            int node = v.get(curr - 1);
            System.out.print(node + ", ");
 
            for (int i = 0; i < adj.get(node).size(); i++) {
                // Adjacent node
                int next = adj.get(node).get(i);
 
                if ((!vis[next]) && (dp[next] < dp[node] + 1)) {
                    // Stores the adjacent node
                    v.add(next);
 
                    // Increases the distance
                    dp[next] = dp[node] + 1;
 
                    // Mark it as visited
                    vis[next] = true;
                }
            }
            curr += 1;
        }
    }
 
    public static void main(String[] args) {
        // No. of nodes in graph
        int N = 4;
 
        // Creating adjacency list
        // for representing graph
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < N + 1; i++) {
            adj.add(new ArrayList<>());
        }
        adj.get(0).add(1);
        adj.get(0).add(2);
        adj.get(1).add(2);
        adj.get(2).add(0);
        adj.get(2).add(3);
        adj.get(3).add(3);
 
        // Following is BFS Traversal
        // starting from vertex 2
        bfsTraversal(adj, N, 2);
    }
}
//This code is contributed by Potta Lokesh


Python3




# C++ implementation to demonstrate
# the above mentioned approach
from queue import Queue
 
# Function to find the distance
# from the source to other nodes
def BFS(curr, N, vis,          dp,  v, adj):
 
    while (curr <= N) :
 
        # Current node
        node = v[curr - 1]
        print(node,end=  ", ")
 
        for i in range(len(adj[node])) :
 
            # Adjacent node
            next = adj[node][i]
 
            if ((not vis[next]) and (dp[next] < dp[node] + 1)) :
 
                # Stores the adjacent node
                v.append(next)
 
                # Increases the distance
                dp[next] = dp[node] + 1
 
                # Mark it as visited
                vis[next] = True
             
         
        curr += 1
     
 
 
# Function to print the distance
# from source to other nodes
def bfsTraversal(adj,    N, source):
    # Initially mark all nodes as false
    vis=[False]*(N + 1)
 
    # Initialize distance array with 0
    dp=[0]*(N + 1); v=[]
 
    v.append(source)
 
    # Initially mark the starting
    # source as 0 and visited as true
    dp = 0
    vis = True
 
    # Call the BFS function
    BFS(1, N, vis, dp, v, adj)
 
 
# Driver code
if __name__ == '__main__':
    # No. of nodes in graph
    N = 4
 
    # Creating adjacency list
    # for representing graph
    adj=[[] for _ in range(N+1)]
    adj[0].append(1)
    adj[0].append(2)
    adj[1].append(2)
    adj[2].append(0)
    adj[2].append(3)
    adj[3].append(3)
 
    # Following is BFS Traversal
    # starting from vertex 2
    bfsTraversal(adj, N, 2)


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find the distance
    // from the source to other nodes
    static void BFS(int curr, int N, bool[] vis,
                   int[] dp, List<int> v,
                   List<List<int>> adj)
    {
        while (curr <= N)
        {
            // Current node
            int node = v[curr - 1];
            Console.Write(node + ", ");
 
            for (int i = 0; i < adj[node].Count; i++)
            {
                // Adjacent node
                int next = adj[node][i];
 
                if ((!vis[next])
                    && (dp[next] < dp[node] + 1))
                {
                    // Stores the adjacent node
                    v.Add(next);
 
                    // Increases the distance
                    dp[next] = dp[node] + 1;
 
                    // Mark it as visited
                    vis[next] = true;
                }
            }
            curr += 1;
        }
    }
 
    // Function to print the distance
    // from source to other nodes
    static void BFS(List<List<int>> adj, int N, int source)
    {
        // Initially mark all nodes as false
        bool[] vis = new bool[N + 1];
 
        // Initialize distance array with 0
        int[] dp = new int[N + 1];
        List<int> v = new List<int>();
 
        v.Add(source);
 
        // Initially mark the starting
        // source as 0 and visited as true
        dp = 0;
        vis = true;
 
        // Call the BFS function
        BFS(1, N, vis, dp, v, adj);
    }
 
    // Driver code
    static void Main(string[] args)
    {
        // No. of nodes in graph
        int N = 4;
 
        // Creating adjacency list
        // for representing graph
        List<List<int>> adj = new List<List<int>>();
        for (int i = 0; i < N + 1; i++)
        {
            adj.Add(new List<int>());
        }
        adj[0].Add(1);
        adj[0].Add(2);
        adj[1].Add(2);
        adj[2].Add(0);
        adj[2].Add(3);
        adj[3].Add(3);
 
        // Following is BFS Traversal
        // starting from vertex 2
        BFS(adj, N, 2);
 
        Console.ReadKey();
    }
}


Javascript




// JavaScript implementation to demonstrate
// the above mentioned approach
 
// Function to find the distance
// from the source to other nodes
function BFS(curr, N, vis, dp, v, adj) {
    while (curr <= N) {
        // Current node
        let node = v[curr - 1];
        console.log(node + ", ");
 
        for (let i = 0; i < adj[node].length; i++) {
            // Adjacent node
            let next = adj[node][i];
 
            if (!vis[next] && (dp[next] < dp[node] + 1)) {
                // Stores the adjacent node
                v.push(next);
 
                // Increases the distance
                dp[next] = dp[node] + 1;
 
                // Mark it as visited
                vis[next] = true;
            }
        }
        curr++;
    }
}
 
// Function to print the distance
// from source to other nodes
function bfsTraversal(adj, N, source) {
    // Initially mark all nodes as false
    let vis = new Array(N + 1).fill(false);
 
    // Initialize distance array with 0
    let dp = new Array(N + 1).fill(0);
    let v = [];
 
    v.push(source);
 
    // Initially mark the starting
    // source as 0 and visited as true
    dp = 0;
    vis = true;
 
    // Call the BFS function
    BFS(1, N, vis, dp, v, adj);
}
 
    // Driver code
     
    // No. of nodes in graph
    let N = 4;
 
    // Creating adjacency list
    // for representing graph
    let adj = new Array(N + 1);
    adj[0] = [1, 2];
    adj[1] = [2];
    adj[2] = [0, 3];
    adj[3] = [3];
 
    // Following is BFS Traversal
    // starting from vertex 2
    bfsTraversal(adj, N, 2);


Output

2, 0, 3, 1, 

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



Previous Article
Next Article

Similar Reads

Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Implementing Water Supply Problem using Breadth First Search
Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which means that water cannot pass through
10 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweighted graph, the shortest path is the path with the l
4 min read
Time and Space Complexity of Breadth First Search (BFS)
What is Breadth First Search?The Breadth First Search (BFS) algorithm is used to search a graph data structure for a node that meets a set of criteria. It starts at the root of the graph and visits all nodes at the current depth level before moving on to the nodes at the next depth level. Although there are other methods for traversing the graph, B
3 min read
Level Order Traversal (Breadth First Search or BFS) of Binary Tree
Level Order Traversal technique is defined as a method to traverse a Tree such that all nodes present in the same level are traversed completely before traversing the next level. Example: Input: Output:12 34 5 Recommended PracticeLevel order traversalTry It!How does Level Order Traversal work?The main idea of level order traversal is to traverse al
16 min read
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 GraphRelation between BFS for Graph and BF
15 min read
Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Breadth First Traversal ( BFS ) on a 2D array
Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0, 1}, {-1, -1, -2, -1}, {-1, -1, -1, -1}, {0, 0, 0,
9 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push (Or Enqueue) in the another Queue. Examples : Inp
9 min read