Give me an implementation of a depth first search
- User
Give me an implementation of a depth first search
Assistant
def dfs(graph, start_node): """ Iterative depth-first search implementation. Args: graph: Dictionary where keys are nodes and values are lists of neighbors start_node: Node to start the search from Returns: List of nodes in the order they were visited """ visited = set() result = [] stack = [start_node] while stack: current = stack.pop() if current not in visited: visited.add(current) result.append(current) # Add neighbors to stack (reversed to maintain expected DFS order) for neighbor in reversed(graph[current]): if neighbor not in visited: stack.append(neighbor) return result # Example usage if __name__ == "__main__": graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } print(dfs(graph, 'A')) # Output: ['A', 'B', 'D', 'E', 'F', 'C']
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.