...

/

Solution: Number of Nodes in a Given Graph Level

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...

Solution

Press + to interact
main.java
Graph.java
class CountNodes {
public static int numberOfNodesInGivenLevel(Graph g, int source, int level) {
int count = 0;
int num_of_vertices = g.getVertices();
// Integer array to hold the history of visited nodes (by default - false)
// Make a node visited whenever you add it into the queue
int visited[] = new int[num_of_vertices];
// Create a linkedlist array called Queue
LinkedList<Integer> queue = new LinkedList<Integer>();
// Mark the visited nodes as true by setting value to 1 and add them to the queue
visited[source] = 1;
queue.add(source);
// Traverse while the queue is not empty
while (queue.size() != 0) {
// Poll the vertex/node from queue
source = queue.poll();
// Get adjacent vertices to the current node from the list
LinkedList<Integer> Llist[];
Llist = g.getAdj();
Iterator<Integer> i = Llist[source].listIterator();
while (i.hasNext()) {
int temp = i.next();
// If not already visited, add to the queue
if (visited[temp] == 0) {
visited[temp] = visited[source] + 1;
if (visited[temp] < level) {
queue.add(temp);
}
}
}
}
// Calculate the count for the level
for (int i = 0; i < num_of_vertices; i++) {
if (visited[i] == level) {
count++;
}
}
return count;
}
}
class Main {
public static void main(String args[]) {
Graph g = new Graph(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(3, 5);
g.addEdge(2, 4);
int answer;
answer = CountNodes.numberOfNodesInGivenLevel(g, 0, 1);
System.out.println(answer);
answer = CountNodes.numberOfNodesInGivenLevel(g, 0, 2);
System.out.println(answer);
answer = CountNodes.numberOfNodesInGivenLevel(g, 0, 3);
System.out.println(answer);
answer = CountNodes.numberOfNodesInGivenLevel(g, 0, 4);
System.out.println(answer);
}
}

Explanation

The solution above modifies the visited array to store the level of each node. Later, it counts the nodes with the same level ( ...

Access this course and 1400+ top-rated courses and projects.