Level of Nodes

Tags : bfs, graph, geeksforgeeks, cpp, medium

Given a Undirected Graph with V vertices and E edges, Find the level of node X. if X does not exist in the graph then print -1. Note: Traverse the graph starting from vertex 0.

Your Task: You dont need to read input or print anything. Your task is to complete the function nodeLevel() which takes two integers V and X denoting the number of vertices and the node, and another adjacency list adj as input parameters and returns the level of Node X. If node X isn’t present it returns -1.

Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)

Examples #

Example 1:

Input:

X = 4
Output:
2
Explanation: 

We can clearly see that Node 4 lies at Level 2.

Constraints #

Solutions #

class Solution
{
    public:
	//Function to find the level of node X.
	int nodeLevel(int V, vector<int> adj[], int X) 
	{
	    // code here
	    queue<pair<int,int>>q;
	    bool vis[V]={0};
	    vis[0]=1;
	    q.push({0,0});
	    while(!q.empty()){
	        auto u=q.front();
	        if(X==u.first)return u.second;
	        q.pop();
	        for(int i:adj[u.first]){
	            if(!vis[i]){
	                q.push({i,u.second+1});
	                vis[i]=true;
	            }
	        }
	    }
	    return -1;
	}
};