Spaces:
Sleeping
Sleeping
| { | |
| "task_id": "task_006_graph_cycle", | |
| "difficulty": "hard", | |
| "description": "Fix the bug in has_cycle. It should detect if a directed graph (given as an adjacency dict) contains a cycle. The current implementation incorrectly reports cycles in DAGs because it doesn't distinguish between nodes in the current DFS path vs. nodes that have been fully explored.", | |
| "buggy_code": "def has_cycle(graph):\n visited = set()\n\n def dfs(node):\n if node in visited:\n return True\n visited.add(node)\n for neighbor in graph.get(node, []):\n if dfs(neighbor):\n return True\n return False\n\n for node in graph:\n if node not in visited:\n if dfs(node):\n return True\n return False\n", | |
| "solution": "def has_cycle(graph):\n visited = set()\n rec_stack = set()\n\n def dfs(node):\n visited.add(node)\n rec_stack.add(node)\n for neighbor in graph.get(node, []):\n if neighbor not in visited:\n if dfs(neighbor):\n return True\n elif neighbor in rec_stack:\n return True\n rec_stack.discard(node)\n return False\n\n for node in graph:\n if node not in visited:\n if dfs(node):\n return True\n return False\n", | |
| "test_descriptions": [ | |
| "A simple cycle A->B->C->A should return True", | |
| "A DAG A->B->C, A->C should return False", | |
| "A self-loop A->A should return True", | |
| "An empty graph {} should return False", | |
| "A disconnected graph with a cycle in one component should return True", | |
| "A diamond DAG A->B, A->C, B->D, C->D should return False" | |
| ], | |
| "test_code": "test_cases = [\n ({\"A\": [\"B\"], \"B\": [\"C\"], \"C\": [\"A\"]}, True, \"simple_cycle\"),\n ({\"A\": [\"B\", \"C\"], \"B\": [\"C\"], \"C\": []}, False, \"dag_no_cycle\"),\n ({\"A\": [\"A\"]}, True, \"self_loop\"),\n ({}, False, \"empty_graph\"),\n ({\"A\": [\"B\"], \"B\": [], \"C\": [\"D\"], \"D\": [\"E\"], \"E\": [\"C\"]}, True, \"disconnected_with_cycle\"),\n ({\"A\": [\"B\", \"C\"], \"B\": [\"D\"], \"C\": [\"D\"], \"D\": []}, False, \"diamond_dag\")\n]\nfor graph, exp, name in test_cases:\n try:\n actual = has_cycle(graph)\n results.append({\"test_name\": name, \"passed\": actual == exp, \"expected\": str(exp), \"actual\": str(actual), \"error\": \"\"})\n except Exception as e:\n results.append({\"test_name\": name, \"passed\": False, \"expected\": str(exp), \"actual\": \"\", \"error\": str(e)})", | |
| "max_steps": 10 | |
| } | |