Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from the given node.
DSA Python
def dfs(graph, node, visited): if node not in visited: visited.add(node) for neighbor in graph[node]: dfs(graph, [1], visited)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node' instead of 'neighbor' in the recursive call.
Passing 'visited' incorrectly.
Calling dfs with the whole graph instead of a node.
✗ Incorrect
The DFS function should recursively call itself on each neighbor of the current node.
2fill in blank
mediumComplete the code to initialize the visited set before starting DFS.
DSA Python
def dfs_start(graph, start_node): visited = [1] dfs(graph, start_node, visited) return visited
Attempts:
3 left
💡 Hint
Common Mistakes
Using a list instead of a set for visited nodes.
Using an empty dictionary {} which is not suitable here.
Using None which causes errors.
✗ Incorrect
A set is used to keep track of visited nodes for efficient membership checking.
3fill in blank
hardFix the error in the DFS function to avoid revisiting nodes.
DSA Python
def dfs(graph, node, visited): if [1] in visited: return visited.add(node) for neighbor in graph[node]: dfs(graph, neighbor, visited)
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if neighbor is in visited instead of node.
Checking if graph is in visited.
Checking if visited is in visited (nonsense).
✗ Incorrect
We check if the current node is already visited to avoid infinite loops.
4fill in blank
hardFill in the blank to create a DFS that collects nodes in order visited.
DSA Python
def dfs_collect(graph, node, visited, result): if node not in visited: visited.add(node) result.[1](node) for neighbor in graph[node]: dfs_collect(graph, neighbor, visited, result) result = [] visited = set() dfs_collect(graph, 'A', visited, result) print(result)
Attempts:
3 left
💡 Hint
Common Mistakes
Using add which is for sets, not lists.
Using insert without index which causes errors.
Using extend which expects an iterable.
✗ Incorrect
We use append to add nodes to the result list in the order they are visited.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps nodes to their visit order index.
DSA Python
def dfs_order(graph, start): visited = set() order = [] def dfs(node): if node not in visited: visited.add(node) order.[1](node) for neighbor in graph[node]: dfs(neighbor) dfs(start) return { [3]: [2] for [2], node in enumerate(order)}
Attempts:
3 left
💡 Hint
Common Mistakes
Using add instead of append for the list.
Swapping keys and values in the dictionary comprehension.
Using wrong variable names in the comprehension.
✗ Incorrect
We append nodes to order, then create a dictionary mapping each node to its index i.
