Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from the given node.
DSA C#
void DFS(int node) {
visited[node] = true;
Console.WriteLine(node);
foreach (var neighbor in graph[node]) {
if (!visited[[1]]) {
DFS(neighbor);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node' instead of 'neighbor' in the visited check.
Checking 'visited' array directly without index.
✗ Incorrect
We check if the neighbor node has been visited before calling DFS on it.
2fill in blank
mediumComplete the code to initialize the visited array for DFS.
DSA C#
int n = graph.Count;
bool[] visited = new bool[[1]];Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 which causes extra unused space.
Using n - 1 which causes out of range errors.
✗ Incorrect
The visited array size should match the number of nodes, which is 'n'.
3fill in blank
hardFix the error in the DFS recursive call to avoid infinite recursion.
DSA C#
void DFS(int node) {
visited[node] = true;
Console.WriteLine(node);
foreach (var neighbor in graph[node]) {
if (!visited[neighbor]) {
DFS([1]);
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling DFS(node) inside the loop instead of DFS(neighbor).
Passing visited[node] which is a boolean, not a node index.
✗ Incorrect
We must call DFS on the neighbor node, not the current node, to avoid infinite recursion.
4fill in blank
hardFill both blanks to create a DFS function that prints nodes and marks them visited.
DSA C#
void DFS(int [1]) { visited[[2]] = true; Console.WriteLine([2]); foreach (var neighbor in graph[[2]]) { if (!visited[neighbor]) { DFS(neighbor); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for parameter and visited index.
Using 'neighbor' instead of 'node' in visited array.
✗ Incorrect
The parameter and the visited index must both be 'node' to correctly mark and print the current node.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps each node to its degree (number of neighbors).
DSA C#
var degrees = new Dictionary<int, int>(); foreach (var [1] in graph.Keys) { degrees[[2]] = graph[[3]].Count; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'neighbor' instead of 'node' as loop variable.
Mixing different variable names for keys.
✗ Incorrect
We iterate over each node key, then assign degrees[node] = graph[node].Count to get the number of neighbors.
