-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.java
56 lines (43 loc) · 1.44 KB
/
App.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package Graph.Question5;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class App {
public static int getNumOfNodesAtGivenLevel(Graph graph, int source, int level) {
int n = graph.getVertices();
List<Integer>[] adjList = graph.getAdjList();
int[] visited = new int[n];
visited[source] = 1;
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
while (!queue.isEmpty()) {
source = queue.poll();
for (int d: adjList[source]) {
if (visited[d] == 0) {
visited[d] = visited[source] + 1;
if (visited[d] < level)
queue.add(d);
}
}
}
int numOfNodes = 0;
for (int i: visited) {
if (i == level)
numOfNodes++;
}
return numOfNodes;
}
public static void main(String[] args){
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 5);
System.out.println(getNumOfNodesAtGivenLevel(graph, 2, 1));
System.out.println(getNumOfNodesAtGivenLevel(graph, 2, 2));
System.out.println(getNumOfNodesAtGivenLevel(graph, 2, 3));
System.out.println(getNumOfNodesAtGivenLevel(graph, 2, 4));
}
}