Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from the given node.
DSA Java
void dfs(int node) {
visited[node] = true;
System.out.print(node + " -> ");
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs([1]);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node' instead of 'neighbor' causes infinite recursion.
Using 'visited' or 'graph' as argument causes errors.
✗ Incorrect
We call dfs recursively on each unvisited neighbor to explore deeper.
2fill in blank
mediumComplete the code to initialize the visited array for DFS.
DSA Java
boolean[] visited = new boolean[[1]];Attempts:
3 left
💡 Hint
Common Mistakes
Using graph[0].length assumes a matrix, but graph is adjacency list.
Using visited.length before initialization causes errors.
✗ Incorrect
The visited array size should match the number of nodes, which is graph.length.
3fill in blank
hardFix the error in the DFS method to avoid revisiting nodes.
DSA Java
void dfs(int node) {
if (visited[node]) return;
visited[node] = true;
System.out.print(node + " -> ");
for (int neighbor : graph[node]) {
dfs([1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling dfs(node) inside the loop causes stack overflow.
Using visited[node] or graph[node] as argument causes errors.
✗ Incorrect
We must call dfs on each neighbor, not the current node, to explore all connected nodes.
4fill in blank
hardFill both blanks to create a DFS method that prints nodes in order.
DSA Java
void dfs(int [1]) { visited[[2]] = true; System.out.print([2] + " -> "); for (int neighbor : graph[[2]]) { if (!visited[neighbor]) { dfs(neighbor); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for parameter and visited index causes errors.
Using 'neighbor' instead of 'node' in visited causes wrong marking.
✗ Incorrect
The parameter and visited index must be the same node variable to mark and print correctly.
5fill in blank
hardFill all three blanks to create a DFS that counts visited nodes.
DSA Java
int count = 0; void dfs(int [1]) { visited[[2]] = true; count[3]; for (int neighbor : graph[[2]]) { if (!visited[neighbor]) { dfs(neighbor); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node++' instead of 'count++' does not increment count.
Using 'neighbor' in visited index causes errors.
✗ Incorrect
Use 'node' as parameter and visited index, and increment count with ++ to track visited nodes.
