Complete the code to start a DFS traversal from the given node.
def dfs(node, visited): if node is None or node in visited: return visited.add(node) for neighbor in node.neighbors: dfs([1], visited)
In DFS, we recursively visit each neighbor of the current node. So, the recursive call should be on neighbor.
Complete the code to mark a node as visited in DFS.
def dfs(node, visited): if node is None or node in visited: return [1].add(node) for neighbor in node.neighbors: dfs(neighbor, visited)
We add the current node to the visited set to mark it as visited and avoid revisiting it.
Fix the error in the DFS code to avoid revisiting nodes.
def dfs(node, visited): if node is None or [1]: return visited.add(node) for neighbor in node.neighbors: dfs(neighbor, visited)
The condition should check if the current node is already in visited to stop revisiting it.
Fill both blanks to create a dictionary comprehension that maps nodes to their depth in DFS.
def dfs_depth(node, depth, depths, visited): if node is None or node in visited: return visited.add(node) depths[node] = depth for neighbor in node.neighbors: dfs_depth(neighbor, depth [1] 1, depths, visited) result = {node: depths[node] for node in depths if depths[node] [2] 2}
We increase depth by 1 when going deeper in DFS, so use +. To filter nodes deeper than 2, use >.
Fill all three blanks to create a dictionary comprehension that maps nodes to their neighbors if the neighbor is unvisited.
def dfs_neighbors(node, visited): return {neighbor: node for neighbor in node.neighbors if neighbor not in [1] visited = set() result = dfs_neighbors([2], visited) visited.add([3])
The comprehension checks neighbors not in visited. We call the function on node and add node to visited.