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
#include <bits/stdc++.h>
using namespace std;
void BFS(int curr, int N, vector<bool>& vis,
vector<int>& dp, vector<int>& v,
vector<vector<int> >& adj)
{
while (curr <= N) {
int node = v[curr - 1];
cout << node << ", ";
for (int i = 0; i < adj[node].size(); i++) {
int next = adj[node][i];
if ((!vis[next])
&& (dp[next] < dp[node] + 1)) {
v.push_back(next);
dp[next] = dp[node] + 1;
vis[next] = true;
}
}
curr += 1;
}
}
void bfsTraversal(
vector<vector<int> >& adj,
int N, int source)
{
vector<bool> vis(N + 1, false);
vector<int> dp(N + 1, 0), v;
v.push_back(source);
dp = 0;
vis = true;
BFS(1, N, vis, dp, v, adj);
}
int main()
{
int N = 4;
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);
bfsTraversal(adj, N, 2);
return 0;
}
|
Java
import java.util.*;
public class Main {
static void bfsTraversal(List<List<Integer>> adj, int N, int source) {
boolean[] vis = new boolean[N + 1];
Arrays.fill(vis, false);
int[] dp = new int[N + 1];
Arrays.fill(dp, 0);
List<Integer> v = new ArrayList<>();
v.add(source);
dp = 0;
vis = true;
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) {
int node = v.get(curr - 1);
System.out.print(node + ", ");
for (int i = 0; i < adj.get(node).size(); i++) {
int next = adj.get(node).get(i);
if ((!vis[next]) && (dp[next] < dp[node] + 1)) {
v.add(next);
dp[next] = dp[node] + 1;
vis[next] = true;
}
}
curr += 1;
}
}
public static void main(String[] args) {
int N = 4;
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);
bfsTraversal(adj, N, 2);
}
}
|
Python3
from queue import Queue
def BFS(curr, N, vis, dp, v, adj):
while (curr <= N) :
node = v[curr - 1]
print(node,end= ", ")
for i in range(len(adj[node])) :
next = adj[node][i]
if ((not vis[next]) and (dp[next] < dp[node] + 1)) :
v.append(next)
dp[next] = dp[node] + 1
vis[next] = True
curr += 1
def bfsTraversal(adj, N, source):
vis=[False]*(N + 1)
dp=[0]*(N + 1); v=[]
v.append(source)
dp = 0
vis = True
BFS(1, N, vis, dp, v, adj)
if __name__ == '__main__':
N = 4
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)
bfsTraversal(adj, N, 2)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void BFS(int curr, int N, bool[] vis,
int[] dp, List<int> v,
List<List<int>> adj)
{
while (curr <= N)
{
int node = v[curr - 1];
Console.Write(node + ", ");
for (int i = 0; i < adj[node].Count; i++)
{
int next = adj[node][i];
if ((!vis[next])
&& (dp[next] < dp[node] + 1))
{
v.Add(next);
dp[next] = dp[node] + 1;
vis[next] = true;
}
}
curr += 1;
}
}
static void BFS(List<List<int>> adj, int N, int source)
{
bool[] vis = new bool[N + 1];
int[] dp = new int[N + 1];
List<int> v = new List<int>();
v.Add(source);
dp = 0;
vis = true;
BFS(1, N, vis, dp, v, adj);
}
static void Main(string[] args)
{
int N = 4;
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);
BFS(adj, N, 2);
Console.ReadKey();
}
}
|
Javascript
function BFS(curr, N, vis, dp, v, adj) {
while (curr <= N) {
let node = v[curr - 1];
console.log(node + ", ");
for (let i = 0; i < adj[node].length; i++) {
let next = adj[node][i];
if (!vis[next] && (dp[next] < dp[node] + 1)) {
v.push(next);
dp[next] = dp[node] + 1;
vis[next] = true;
}
}
curr++;
}
}
function bfsTraversal(adj, N, source) {
let vis = new Array(N + 1).fill(false);
let dp = new Array(N + 1).fill(0);
let v = [];
v.push(source);
dp = 0;
vis = true;
BFS(1, N, vis, dp, v, adj);
}
let N = 4;
let adj = new Array(N + 1);
adj[0] = [1, 2];
adj[1] = [2];
adj[2] = [0, 3];
adj[3] = [3];
bfsTraversal(adj, N, 2);
|
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
08 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...