Solution: Number of Nodes in a Given Graph Level
This review provides a detailed analysis of the different ways to calculate the number of nodes in an undirected graph level.
We'll cover the following...
We'll cover the following...
Solution
Explanation
The solution above modifies the visited array to store the level of each node. Later, it counts the nodes with the same level (lines 34-38).
In this code, while visiting each node, the level of the visited node is set with an increment in the level of its parent node, i.e.,
visited[child] = visited[parent] + 1
This is how the level of each node is determined (line 26).
Time complexity
Its time complexity is the same as the breadth-first traversal algorithm. We haven’t added any new loops. We just added a simple array to do our job.
The time complexity of BFS can be computed as the total number of iterations performed by the loop.
Let ...