Write me some code that can do DFS traversal.
- User
Write me some code that can do DFS traversal.
- Assistant
Certainly! Here's an example of code that performs Depth-First Search (DFS) traversal on a graph represented as an adjacency list:
# Function to perform DFS traversal def dfs(graph, start): visited = set() # Set to keep track of visited nodes stack = [start] # Stack to store nodes to visit while stack: node = stack.pop() # Get the next node from the stack if node not in visited: print(node, end=" ") # Process the node visited.add(node) # Mark the node as visited # Add the neighboring nodes to the stack stack.extend(graph[node]) # Example usage adjacency_list = { 1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [6], 6: [] } dfs(adjacency_list, 1) # Start DFS traversal from node 1
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.