Problem Statement

Given a connected undirected graph. Perform a Breadth First Traversal of the graph.

Problem Link

BFS of graph | Practice | GeeksforGeeks

Code

class Solution
{
    public:
    //Function to return Breadth First Traversal of given graph.
	vector<int>bfsOfGraph(int V, vector<int> adj[])
	{
	    vector<int> res;
	    queue<int> q;
	    vector<bool> visited(V,false);
	    
	    q.push(0);
	    visited[0] = true;
	    
	    while(!q.empty())
	    {
	        int u = q.front();
	        
	        res.push_back(u);
	        
	        for(int v:adj[u])
	        {
	            if(!visited[v])
	            {
	                visited[v] = true;
	                q.push(v);
	            }
	        }
	        q.pop();
	    }
	    return res;

	}
};