Create a programming task related to common algorithms and data…
- User
Assistant: User: Create a programming task related to common algorithms and data structures. The task should follow this format:
{ "problem_description": "", "input": "", "output": "", "examples": [ { "input": "", "output": "", "explanation": "" }, { "input": "", "output": "", "explanation": "" }, { "input": "", "output": "", "explanation": "" }, { "input": "", "output": "", "explanation": "" } ], "function_signature": "", "solution": { "code": "" } }
Assistant:
- Assistant
{ "problem_description": "Implement the Depth First Search (DFS) algorithm to find all the nodes reachable from a given starting node in a directed graph. A graph is represented as an adjacency list where each node has a list of its direct neighbors.", "input": "The function takes two arguments: (1) graph: a dictionary representing an adjacency list of the graph, where keys are nodes and values are lists of neighboring nodes, (2) start_node: an integer or string representing the node from which to start the search.", "output": "A list containing all nodes reachable from the start_node using DFS, in the order they were first visited.", "examples": [ { "input": "graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['E'], 'D': [], 'E': ['F'], 'F': []}, start_node = 'A'", "output": "['A', 'B', 'D', 'C', 'E', 'F']", "explanation": "Starting from 'A', the DFS visits 'B', then 'D'. Backtracks to 'A', and visits 'C', then 'E'. Finally, it visits 'F'." }, { "input": "graph = {'1': ['2', '3'], '2': ['4'], '3': [], '4': []}, start_node = '1'", "output": "['1', '2', '4', '3']", "explanation": "Starting from '1', the DFS visits '2', then '4'. Backtracks to '1', and visits '3'." }, { "input": "graph = {'X': [], 'Y': ['Z'], 'Z': ['Y']}, start_node = 'Y'", "output": "['Y', 'Z']", "explanation": "Starting from 'Y', the DFS visits 'Z', which leads back to 'Y'. However, 'Y' is already visited." }, { "input": "graph = {'node1': ['node2'], 'node2': ['node3'], 'node3': ['node1']}, start_node = 'node1'", "output": "['node1', 'node2', 'node3']", "explanation": "DFS visits all nodes forming a cycle starting from 'node1'." } ], "function_signature": "def dfs(graph: dict, start_node: str) -> list:", "solution": { "code": "def dfs(graph, start_node):\n visited = []\n stack = [start_node]\n \n while stack:\n node = stack.pop()\n if node not in visited:\n visited.append(node)\n # Add neighbors to stack\n stack.extend(reversed(graph[node])) # Reverse to maintain order\n \n return visited" } }