Level of Nodes | Practice | GeeksforGeeks

PHOTO EMBED

Thu Oct 19 2023 07:20:10 GMT+0000 (Coordinated Universal Time)

Saved by @DxBros #bfs #graphs #easy

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

This was a simple bfs traversal

https://practice.geeksforgeeks.org/problems/level-of-nodes-1587115620/1