Solution: Calculate the Number of Nodes in a Graph Level
Review the solution to calculate the number of nodes at a given level in a graph in detail.
We'll cover the following...
Solution
class Program{/// <summary>/// Calculates the number of nodes at a given level in the graph./// </summary>/// <param name="graph">The graph.</param>/// <returns>The total number of nodes at the given level.</returns>public static int NumberOfNodes(Graph myGraph, int level){int source = 0;// Mark all the vertices as not visited// All element are instantiated to 0 by defaultint[] visited = new int[myGraph.graph.Length];// Create a queueQueue<int> queue = new Queue<int>();// Mark the source node as// visited and enqueue itqueue.Enqueue(source);visited[source] = 1;while (queue.Count != 0){// Dequeue a vertex from queuesource = queue.Dequeue();// Get all adjacent vertices of the// dequeued vertex source. If a adjacent// has not been visited, then mark it// visited and enqueue itwhile (myGraph.graph[source] != null){int data = myGraph.graph[source].Vertex;if (visited[data] == 0){queue.Enqueue(data);visited[data] = visited[source] + 1;}myGraph.graph[source] = myGraph.graph[source].Next;}}// Counting number of nodes at given levelint result = 0;for (int i = 0; i < myGraph.graph.Length; i++){if (visited[i] == level){result += 1;}}return result;}// Main to test above functionstatic void Main(string[] args){int V = 5;Graph g = new Graph(V);g.AddEdge(0, 1);g.AddEdge(0, 2);g.AddEdge(1, 3);g.AddEdge(1, 4);Console.WriteLine(NumberOfNodes(g, 2));}}
Explanation
The solution above modifies the visited list to store the level of each node. Later, we count the nodes with the same level.
In this code, while visiting each node, the level of that 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.
Time complexity
Its time complexity is the same as the breadth-first traversal algorithm. We have added no new loops, just a simple list to do our job.
The time complexity of BFS can be computed as the total number of iterations performed by the loop.
Let ...