19. Level of Nodes
Last updated
Last updated
The problem can be found at the following link: Question Link
For any question that involves determining the level of, by intuition, we have to implement the Breadth-First Search (BFS) algorithm.
To begin, we do a BFS traversal from node 0 within the graph, seeking to determine the level of the specified node X.
Here is the process:
Use a queue to keep track of nodes that need visiting and a vector to record the level of each visited node.
For each node visited during the BFS, explore its adjacent nodes, marking them as visited and updating their levels.
Continue the BFS until all reachable nodes are visited or until the queue is empty.
If the target node X
is visited, return its level. If it remains unvisited, return -1
.
Time Complexity: O(V + E)
, where V
is the number of nodes (vertices) and E
is the number of edges in the graph.
Auxiliary Space Complexity: O(V)
, where V
is the number of nodes.
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.