Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a graph using adjacency list.
DSA C#
Dictionary<int, List<int>> graph = new Dictionary<int, List<int>>(); graph.Add(1, new List<int> { [1] });
Attempts:
3 left
💡 Hint
Common Mistakes
Adding only one neighbor when multiple neighbors exist.
Adding the node itself as its neighbor.
✗ Incorrect
The adjacency list for node 1 should contain its neighbors. Here, nodes 2 and 3 are neighbors, so we add both.
2fill in blank
mediumComplete the code to check if a node exists in the graph.
DSA C#
if (graph.[1](3)) { Console.WriteLine("Node 3 exists"); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using ContainsValue which checks values, not keys.
Using a non-existent method like HasKey.
✗ Incorrect
ContainsKey checks if the dictionary has a specific key, which is the node here.
3fill in blank
hardFix the error in the code to add an edge between nodes 2 and 3.
DSA C#
graph[2].Add([1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Adding the same node number (2) instead of the neighbor.
Adding a node not connected to 2.
✗ Incorrect
To add an edge from node 2 to node 3, we add 3 to the adjacency list of node 2.
4fill in blank
hardFill both blanks to create a method that returns true if a path exists between two nodes.
DSA C#
bool PathExists(int start, int end) {
var visited = new HashSet<int>();
var queue = new Queue<int>();
queue.Enqueue(start);
while (queue.Count > 0) {
int current = queue.Dequeue();
if (current [1] end) return true;
visited.Add(current);
foreach (var neighbor in graph[current]) {
if (!visited.Contains(neighbor)) {
queue.[2](neighbor);
}
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' in the if condition.
Using 'Add' instead of 'Enqueue' for the queue.
✗ Incorrect
We check if current equals end to find the path. We add neighbors to the queue using Enqueue.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps nodes to their degrees (number of neighbors).
DSA C#
var degrees = new Dictionary<int, int>(); foreach (var node in graph.Keys) { degrees[[1]] = graph[[2]].[3]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Length' which is not valid for List in C#.
Using different variables instead of 'node'.
✗ Incorrect
We use 'node' as the key and index, and 'Count' to get the number of neighbors in the list.
