3. Consider the following C# code snippet representing a graph and a tree. What will be the output when checking if the graph contains a cycle?
class Node {
public int Value;
public List<Node> Neighbors = new List<Node>();
}
bool HasCycle(Node node, HashSet<Node> visited, Node parent) {
visited.Add(node);
foreach (var neighbor in node.Neighbors) {
if (!visited.Contains(neighbor)) {
if (HasCycle(neighbor, visited, node)) return true;
} else if (neighbor != parent) {
return true;
}
}
return false;
}
// Setup
Node a = new Node { Value = 1 };
Node b = new Node { Value = 2 };
Node c = new Node { Value = 3 };
a.Neighbors.Add(b);
b.Neighbors.Add(a);
b.Neighbors.Add(c);
c.Neighbors.Add(b);
c.Neighbors.Add(a); // extra edge creating a cycle
var visited = new HashSet<Node>();
Console.WriteLine(HasCycle(a, visited, null));