Advanced Topics MCQ
Code Tracing: Graphs and Graph Theory
Code Tracing: Graphs and Graph Theory
Question 1 of 25
Answered 0 of 25
Choose one answer.
What sequence is printed by breadth-first search using the adjacency-list order shown?
import java.util.LinkedList;
import java.util.Queue;
public class BfsTrace
{
public static void main(String[] args)
{
int[][] graph = {{1, 2}, {3}, {3, 4}, {5}, {5}, {}};
boolean[] visited = new boolean[graph.length];
Queue<Integer> q = new LinkedList<Integer>();
q.add(0); visited[0] = true;
String out = "";
while (!q.isEmpty())
{
int node = q.remove();
out += node + " ";
for (int next : graph[node])
if (!visited[next]) { visited[next] = true; q.add(next); }
}
System.out.println(out.trim());
}
}