Breadth First Search (BFS) is a graph traversal algorithm that starts from a source node and explores the graph level by level. First, it visits all nodes directly adjacent to the source. Then, it moves on to visit the adjacent nodes of those nodes, and this process continues until all reachable nodes are visited.
BFS is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level.
The algorithm starts from a given source vertex and explores all vertices reachable from that source, visiting nodes in increasing order of their distance from the source, level by level using a queue. Since graphs may contain cycles, a vertex could be visited multiple times. To prevent revisiting a vertex, a visited array is used.
Let us understand the working of Breadth First Search with the help of the following Illustration:
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>usingnamespacestd;//Driver Code Ends// BFS for single connected componentvector<int>bfs(vector<vector<int>>&adj){intV=adj.size();vector<bool>visited(V,false);vector<int>res;queue<int>q;intsrc=0;visited[src]=true;q.push(src);while(!q.empty()){intcurr=q.front();q.pop();res.push_back(curr);// visit all the unvisited// neighbours of current nodefor(intx:adj[curr]){if(!visited[x]){visited[x]=true;q.push(x);}}}returnres;}//Driver Code StartsvoidaddEdge(vector<vector<int>>&adj,intu,intv){adj[u].push_back(v);adj[v].push_back(u);}intmain(){intV=5;vector<vector<int>>adj(V);// creating adjacency listaddEdge(adj,1,2);addEdge(adj,1,0);addEdge(adj,2,0);addEdge(adj,2,3);addEdge(adj,2,4);vector<int>res=bfs(adj);for(inti:res)cout<<i<<" ";}//Driver Code Ends
C
//Driver Code Starts#include<stdio.h>#define V 5#define MAXQ 100//Driver Code Ends// BFS for single connected componentvoidbfs(intadj[V][V],intres[V],int*resSize){intvisited[V]={0};intq[MAXQ];intfront=0,rear=0;intsrc=0;visited[src]=1;q[rear++]=src;while(front<rear){intcurr=q[front++];res[(*resSize)++]=curr;// visit all the unvisited// neighbours of current nodefor(intx=0;x<V;x++){if(adj[curr][x]&&!visited[x]){visited[x]=1;q[rear++]=x;}}}}//Driver Code StartsvoidaddEdge(intadj[V][V],intu,intv){adj[u][v]=1;adj[v][u]=1;// undirected}intmain(){intadj[V][V]={0};// creating adjacency listaddEdge(adj,1,2);addEdge(adj,1,0);addEdge(adj,2,0);addEdge(adj,2,3);addEdge(adj,2,4);intres[V];intresSize=0;bfs(adj,res,&resSize);for(inti=0;i<resSize;i++)printf("%d ",res[i]);return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.ArrayList;importjava.util.Queue;importjava.util.LinkedList;classGFG{//Driver Code Ends// BFS for single connected componentstaticArrayList<Integer>bfs(ArrayList<ArrayList<Integer>>adj){intV=adj.size();boolean[]visited=newboolean[V];ArrayList<Integer>res=newArrayList<>();intsrc=0;Queue<Integer>q=newLinkedList<>();visited[src]=true;q.add(src);while(!q.isEmpty()){intcurr=q.poll();res.add(curr);// visit all the unvisited// neighbours of current nodefor(intx:adj.get(curr)){if(!visited[x]){visited[x]=true;q.add(x);}}}returnres;}//Driver Code StartsstaticvoidaddEdge(ArrayList<ArrayList<Integer>>adj,intu,intv){adj.get(u).add(v);adj.get(v).add(u);}publicstaticvoidmain(String[]args){intV=5;ArrayList<ArrayList<Integer>>adj=newArrayList<>();// creating adjacency listfor(inti=0;i<V;i++)adj.add(newArrayList<>());addEdge(adj,1,2);addEdge(adj,1,0);addEdge(adj,2,0);addEdge(adj,2,3);addEdge(adj,2,4);ArrayList<Integer>res=bfs(adj);for(intx:res)System.out.print(x+" ");}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque#Driver Code Ends# BFS for single connected componentdefbfs(adj):V=len(adj)visited=[False]*Vres=[]src=0q=deque()visited[src]=Trueq.append(src)whileq:curr=q.popleft()res.append(curr)# visit all the unvisited# neighbours of current nodeforxinadj[curr]:ifnotvisited[x]:visited[x]=Trueq.append(x)returnres#Driver Code StartsdefaddEdge(adj,u,v):adj[u].append(v)adj[v].append(u)if__name__=="__main__":V=5adj=[]# creating adjacency listforiinrange(V):adj.append([])addEdge(adj,1,2)addEdge(adj,1,0)addEdge(adj,2,0)addEdge(adj,2,3)addEdge(adj,2,4)res=bfs(adj)fornodeinres:print(node,end=" ")#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code Ends// BFS for single connected componentstaticList<int>bfs(List<List<int>>adj){intV=adj.Count;bool[]visited=newbool[V];List<int>res=newList<int>();intsrc=0;Queue<int>q=newQueue<int>();visited[src]=true;q.Enqueue(src);while(q.Count>0){intcurr=q.Dequeue();res.Add(curr);// visit all the unvisited// neighbours of current nodeforeach(intxinadj[curr]){if(!visited[x]){visited[x]=true;q.Enqueue(x);}}}returnres;}//Driver Code StartsstaticvoidaddEdge(List<List<int>>adj,intu,intv){adj[u].Add(v);adj[v].Add(u);}staticvoidMain(){intV=5;List<List<int>>adj=newList<List<int>>();// creating adjacency listfor(inti=0;i<V;i++)adj.Add(newList<int>());addEdge(adj,1,2);addEdge(adj,1,0);addEdge(adj,2,0);addEdge(adj,2,3);addEdge(adj,2,4);List<int>res=bfs(adj);foreach(intiinres)Console.Write(i+" ");}}//Driver Code Ends
JavaScript
//Driver Code StartsconstDenque=require("denque");//Driver Code Ends// BFS for single connected componentfunctionbfs(adj){constV=adj.length;constvisited=newArray(V).fill(false);constres=[];constq=newDenque();letsrc=0;visited[src]=true;q.push(src);while(!q.isEmpty()){constcurr=q.shift();res.push(curr);// visit all the unvisited// neighbours of current nodefor(constxofadj[curr]){if(!visited[x]){visited[x]=true;q.push(x);}}}returnres;}//Driver Code StartsfunctionaddEdge(adj,u,v){adj[u].push(v);adj[v].push(u);}// Driver codeletV=5;letadj=[];// creating adjacency listfor(leti=0;i<V;i++)adj.push([]);addEdge(adj,1,2);addEdge(adj,1,0);addEdge(adj,2,0);addEdge(adj,2,3);addEdge(adj,2,4);constres=bfs(adj);for(leti=0;i<res.length;i++){process.stdout.write(res[i]+" ");}//Driver Code Ends
Output
0 1 2 3 4
Time Complexity: O(V + E), BFS explores all the vertices and edges in the graph. It visits every vertex and edge only once. Auxiliary Space: O(V), Using a queue to keep track of the vertices that need to be visited.
BFS of a Disconnected Undirected Graph:
In a disconnected graph, some vertices may not be reachable from a single source. To ensure all vertices are visited in BFS traversal, we iterate through each vertex, and if any vertex is unvisited, we perform a BFS starting from that vertex being the source. This way, BFS explores every connected component of the graph.
C++
//Driver Code Starts#include<iostream>#include<vector>#include<queue>usingnamespacestd;//Driver Code Ends// BFS for a single connected componentvoidbfsConnected(vector<vector<int>>&adj,intsrc,vector<bool>&visited,vector<int>&res){queue<int>q;visited[src]=true;q.push(src);while(!q.empty()){intcurr=q.front();q.pop();res.push_back(curr);// visit all the unvisited// neighbours of current nodefor(intx:adj[curr]){if(!visited[x]){visited[x]=true;q.push(x);}}}}// BFS for all components (handles disconnected graphs)vector<int>bfs(vector<vector<int>>&adj){intV=adj.size();vector<bool>visited(V,false);vector<int>res;for(inti=0;i<V;i++){if(!visited[i])bfsConnected(adj,i,visited,res);}returnres;}//Driver Code StartsvoidaddEdge(vector<vector<int>>&adj,intu,intv){adj[u].push_back(v);adj[v].push_back(u);}intmain(){intV=6;vector<vector<int>>adj(V);// creating adjacency listaddEdge(adj,1,2);addEdge(adj,2,0);addEdge(adj,0,3);addEdge(adj,4,5);vector<int>res=bfs(adj);for(inti:res)cout<<i<<" ";}//Driver Code Ends
C
//Driver Code Starts#include<stdio.h>#define V 6#define MAXQ 100//Driver Code Ends// BFS for a single connected componentvoidbfsConnected(intadj[V][V],intsrc,intvisited[V],intres[V],int*resSize){intq[MAXQ];intfront=0,rear=0;visited[src]=1;q[rear++]=src;while(front<rear){intcurr=q[front++];res[(*resSize)++]=curr;// visit all the unvisited// neighbours of current nodefor(intx=0;x<V;x++){if(adj[curr][x]&&!visited[x]){visited[x]=1;q[rear++]=x;}}}}// BFS for all components (handles disconnected graphs)voidbfs(intadj[V][V],intres[V],int*resSize){intvisited[V]={0};for(inti=0;i<V;i++){if(!visited[i])bfsConnected(adj,i,visited,res,resSize);}}//Driver Code StartsvoidaddEdge(intadj[V][V],intu,intv){adj[u][v]=1;adj[v][u]=1;}intmain(){intadj[V][V]={0};addEdge(adj,1,2);addEdge(adj,2,0);addEdge(adj,0,3);addEdge(adj,4,5);intres[V];intresSize=0;bfs(adj,res,&resSize);for(inti=0;i<resSize;i++)printf("%d ",res[i]);return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.ArrayList;importjava.util.Queue;importjava.util.LinkedList;classGfG{//Driver Code Ends// BFS for a single connected componentstaticvoidbfsConnected(ArrayList<ArrayList<Integer>>adj,intsrc,boolean[]visited,ArrayList<Integer>res){Queue<Integer>q=newLinkedList<>();visited[src]=true;q.add(src);while(!q.isEmpty()){intcurr=q.poll();res.add(curr);// visit all the unvisited// neighbours of current nodefor(intx:adj.get(curr)){if(!visited[x]){visited[x]=true;q.add(x);}}}}// BFS for all components (handles disconnected graphs)staticArrayList<Integer>bfs(ArrayList<ArrayList<Integer>>adj){intV=adj.size();boolean[]visited=newboolean[V];ArrayList<Integer>res=newArrayList<>();for(inti=0;i<V;i++){if(!visited[i])bfsConnected(adj,i,visited,res);}returnres;}//Driver Code StartsstaticvoidaddEdge(ArrayList<ArrayList<Integer>>adj,intu,intv){adj.get(u).add(v);adj.get(v).add(u);}publicstaticvoidmain(String[]args){intV=6;ArrayList<ArrayList<Integer>>adj=newArrayList<>();// creating adjacency listfor(inti=0;i<V;i++)adj.add(newArrayList<>());addEdge(adj,1,2);addEdge(adj,2,0);addEdge(adj,0,3);addEdge(adj,4,5);ArrayList<Integer>res=bfs(adj);for(intx:res)System.out.print(x+" ");}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque#Driver Code Ends# BFS for a single connected componentdefbfsConnected(adj,src,visited,res):q=deque()visited[src]=Trueq.append(src)whileq:curr=q.popleft()res.append(curr)# visit all the unvisited# neighbours of current nodeforxinadj[curr]:ifnotvisited[x]:visited[x]=Trueq.append(x)# BFS for all components (handles disconnected graphs)defbfs(adj):V=len(adj)visited=[False]*Vres=[]foriinrange(V):ifnotvisited[i]:bfsConnected(adj,i,visited,res)returnres#Driver Code StartsdefaddEdge(adj,u,v):adj[u].append(v)adj[v].append(u)if__name__=="__main__":V=6adj=[]# creating adjacency listforiinrange(V):adj.append([])addEdge(adj,1,2)addEdge(adj,2,0)addEdge(adj,0,3)addEdge(adj,4,5)res=bfs(adj)fornodeinres:print(node,end=" ")#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code Ends// BFS for a single connected componentstaticvoidbfsConnected(List<List<int>>adj,intsrc,bool[]visited,List<int>res){Queue<int>q=newQueue<int>();visited[src]=true;q.Enqueue(src);while(q.Count>0){intcurr=q.Dequeue();res.Add(curr);// visit all the unvisited// neighbours of current nodeforeach(intxinadj[curr]){if(!visited[x]){visited[x]=true;q.Enqueue(x);}}}}// BFS for all components (handles disconnected graphs)staticList<int>bfs(List<List<int>>adj){intV=adj.Count;bool[]visited=newbool[V];List<int>res=newList<int>();for(inti=0;i<V;i++){if(!visited[i])bfsConnected(adj,i,visited,res);}returnres;}//Driver Code StartsstaticvoidaddEdge(List<List<int>>adj,intu,intv){adj[u].Add(v);adj[v].Add(u);}staticvoidMain(){intV=6;List<List<int>>adj=newList<List<int>>();// creating adjacency listfor(inti=0;i<V;i++)adj.Add(newList<int>());addEdge(adj,1,2);addEdge(adj,2,0);addEdge(adj,0,3);addEdge(adj,4,5);List<int>res=bfs(adj);foreach(intiinres)Console.Write(i+" ");}}//Driver Code Ends
JavaScript
//Driver Code Starts// BFS for a single connected componentfunctionbfsConnected(adj,src,visited,res){//Driver Code Endsconstq=[];visited[src]=true;q.push(src);while(q.length>0){// dequeueconstcurr=q.shift();res.push(curr);// visit all the unvisited neighboursfor(constxofadj[curr]){if(!visited[x]){visited[x]=true;// enqueueq.push(x);}}}}// BFS for all components (handles disconnected graphs)functionbfs(adj){constV=adj.length;constvisited=newArray(V).fill(false);constres=[];for(leti=0;i<V;i++){if(!visited[i])bfsConnected(adj,i,visited,res);}returnres;}functionaddEdge(adj,u,v){adj[u].push(v);//Driver Code Startsadj[v].push(u);}// Driver codeletV=6;letadj=[];// creating adjacency listfor(leti=0;i<V;i++)adj.push([]);addEdge(adj,1,2);addEdge(adj,2,0);addEdge(adj,0,3);addEdge(adj,4,5);constres=bfs(adj);for(constnumofres){process.stdout.write(num+" ");}//Driver Code Ends
Output
0 2 3 1 4 5
Time Complexity: O(V + E), The for loop ensures BFS starts from every unvisited vertex to cover all components, but the visited array ensures each vertex and edge is processed only once, keeping the total time complexity to be linear.
Auxiliary Space: O(V), using a queue to keep track of the vertices that need to be visited.
Applications of BFS in Graphs
BFS has various applications in graph theory and computer science, including:
Shortest Path Finding
Cycle Detection
Connected Components
Network Routing
To read more about applications of BFS, read this article.