...

/

Solution: Calculate the Number of Nodes in a Graph Level

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 default
int[] visited = new int[myGraph.graph.Length];
// Create a queue
Queue<int> queue = new Queue<int>();
// Mark the source node as
// visited and enqueue it
queue.Enqueue(source);
visited[source] = 1;
while (queue.Count != 0)
{
// Dequeue a vertex from queue
source = queue.Dequeue();
// Get all adjacent vertices of the
// dequeued vertex source. If a adjacent
// has not been visited, then mark it
// visited and enqueue it
while (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 level
int result = 0;
for (int i = 0; i < myGraph.graph.Length; i++)
{
if (visited[i] == level)
{
result += 1;
}
}
return result;
}
// Main to test above function
static 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, ...