Complete the code to initialize the adjacency list for the graph.
graph = {i: [] for i in range([1])}We use n to create keys for all nodes from 0 to n-1 in the adjacency list.
Complete the code to add edges to the adjacency list for an undirected graph.
graph[u].append([1])
graph[v].append(u)u to u's list.For undirected graphs, add v to u's list and u to v's list.
Fix the error in the DFS function to correctly detect cycles.
def dfs(node, parent): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: if dfs(neighbor, [1]): return True elif neighbor != parent: return True return False
We pass node as the parent for the next DFS call to avoid false cycle detection.
Fill both blanks to complete the cycle detection loop over all nodes.
for i in range([1]): if i not in [2]: if dfs(i, -1): print("Cycle detected") break
Loop over all nodes from 0 to n-1 and check if each node is visited before DFS.
Fill all three blanks to complete the function that returns True if a cycle exists.
def has_cycle(graph, [1]): visited = set() for node in graph: if node not in visited: if dfs(node, [2]): return [3] return False
The function takes n (number of nodes), starts DFS with parent -1, and returns True if a cycle is found.
