3. Consider the following Java code snippet representing a graph and a tree. What will be the output when checking if the graph has cycles?
class GraphNode {
int val;
List<GraphNode> neighbors = new ArrayList<>();
}
boolean hasCycle(GraphNode node, Set<GraphNode> visited, Set<GraphNode> recStack) {
if (recStack.contains(node)) return true;
if (visited.contains(node)) return false;
visited.add(node);
recStack.add(node);
for (GraphNode neighbor : node.neighbors) {
if (hasCycle(neighbor, visited, recStack)) return true;
}
recStack.remove(node);
return false;
}
// Setup
GraphNode a = new GraphNode(); a.val = 1;
GraphNode b = new GraphNode(); b.val = 2;
GraphNode c = new GraphNode(); c.val = 3;
a.neighbors.add(b);
b.neighbors.add(c);
c.neighbors.add(a); // cycle here
System.out.println(hasCycle(a, new HashSet<>(), new HashSet<>()));