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;
}
};
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter