3. What will be the output of the following Java code snippet detecting cycle in an undirected graph?
import java.util.*;
public class GraphCycle {
static boolean dfs(int node, int parent, boolean[] visited, List graph) {
visited[node] = true;
for (int adj : graph.get(node)) {
if (!visited[adj]) {
if (dfs(adj, node, visited, graph)) return true;
} else if (adj != parent) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int n = 4;
List graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
graph.get(0).add(1); graph.get(1).add(0);
graph.get(1).add(2); graph.get(2).add(1);
graph.get(2).add(3); graph.get(3).add(2);
graph.get(3).add(1); graph.get(1).add(3);
boolean[] visited = new boolean[n];
boolean hasCycle = false;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
if (dfs(i, -1, visited, graph)) {
hasCycle = true;
break;
}
}
}
System.out.println(hasCycle);
}
}