Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the distance array with infinity except the source vertex.
DSA C#
int[] dist = new int[V]; for (int i = 0; i < V; i++) { dist[i] = [1]; } dist[src] = 0;
Attempts:
3 left
💡 Hint
Common Mistakes
Setting distance to 0 for all vertices instead of only source.
Using -1 as initial distance which is incorrect.
✗ Incorrect
We use int.MaxValue to represent infinity for initial distances except the source which is 0.
2fill in blank
mediumComplete the code to relax edges inside the main loop of Bellman-Ford.
DSA C#
for (int i = 1; i <= V - 1; i++) { foreach (var edge in edges) { int u = edge.src; int v = edge.dest; int weight = edge.weight; if (dist[u] != [1] && dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Not checking if dist[u] is infinity before adding weight.
Using 0 or -1 instead of int.MaxValue in the condition.
✗ Incorrect
We check if dist[u] is not infinity (int.MaxValue) before relaxing to avoid overflow.
3fill in blank
hardFix the error in the negative cycle detection condition.
DSA C#
foreach (var edge in edges) { int u = edge.src; int v = edge.dest; int weight = edge.weight; if (dist[u] != int.MaxValue && dist[u] + weight [1] dist[v]) { Console.WriteLine("Graph contains negative weight cycle"); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '>=' which is incorrect for negative cycle detection.
Using '==' which does not detect negative cycles.
✗ Incorrect
If we can still relax an edge (dist[u] + weight < dist[v]) after V-1 iterations, a negative cycle exists.
4fill in blank
hardFill both blanks to complete the edge relaxation inside the Bellman-Ford main loop.
DSA C#
for (int i = 1; i <= V - 1; i++) { foreach (var edge in edges) { int u = edge.src; int v = edge.dest; int weight = edge.weight; if (dist[u] != [1] && dist[u] + weight [2] dist[v]) { dist[v] = dist[u] + weight; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operator in relaxation condition.
Not checking for infinity before relaxation.
✗ Incorrect
We check dist[u] != int.MaxValue and relax if dist[u] + weight < dist[v].
5fill in blank
hardFill all three blanks to complete the dictionary comprehension that stores shortest distances after Bellman-Ford.
DSA C#
var shortestPaths = new Dictionary<int, int>(); for (int i = 0; i < V; i++) { if (dist[i] != [1]) { shortestPaths[[2]] = dist[[3]]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong key or value indices in dictionary.
Not checking for int.MaxValue before adding.
✗ Incorrect
We skip vertices with distance int.MaxValue and store distances keyed by vertex index i.
