Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the distance vector with infinity except the source vertex.
DSA Rust
let mut dist = vec![[1]; graph.len()]; dist[source] = 0;
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for all distances which makes all nodes appear reachable immediately.
Using -1 which is invalid for usize type.
✗ Incorrect
We initialize distances to the maximum usize value to represent infinity, except the source which is zero.
2fill in blank
mediumComplete the code to relax edges inside the main loop of Bellman-Ford.
DSA Rust
for &(u, v, w) in edges.iter() { if dist[u] != usize::MAX && dist[u] [1] dist[v].saturating_sub(w) { dist[v] = dist[u].saturating_add(w); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' in the wrong direction causing no updates.
Using '==' which prevents relaxation.
✗ Incorrect
Relaxation happens if the current distance to u plus edge weight is less than the current distance to v.
3fill in blank
hardFix the error in the negative cycle detection loop condition.
DSA Rust
for &(u, v, w) in edges.iter() { if dist[u] != usize::MAX && dist[u] [1] dist[v].saturating_sub(w) { return true; // Negative cycle detected } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' or '==' which do not correctly detect negative cycles.
Using '<' which reverses the logic.
✗ Incorrect
A negative cycle exists if we can still relax an edge, meaning dist[u] + w < dist[v].
4fill in blank
hardFill both blanks to complete the main relaxation loop and the iteration count.
DSA Rust
for _ in 0..[1] { for &(u, v, w) in edges.iter() { if dist[u] != usize::MAX && dist[u] [2] dist[v].saturating_sub(w) { dist[v] = dist[u].saturating_add(w); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using graph.len() instead of graph.len() - 1 for iterations.
Using '>' instead of '<' in relaxation condition.
✗ Incorrect
The Bellman-Ford algorithm relaxes edges |V|-1 times, and relaxation happens if dist[u] + w < dist[v].
5fill in blank
hardFill all three blanks to complete the function signature, return type, and negative cycle detection.
DSA Rust
fn bellman_ford(graph: &Vec<Vec<(usize, i32)>>, source: usize) -> (Vec<i32>, bool) {
let mut dist = vec![[1]; graph.len()];
dist[source] = 0;
let mut edges = Vec::new();
for u in 0..graph.len() {
for &(v, w) in &graph[u] {
edges.push((u, v, w));
}
}
for _ in 0..graph.len() - 1 {
for &(u, v, w) in edges.iter() {
if dist[u] != [2] && dist[u] + w < dist[v] {
dist[v] = dist[u] + w;
}
}
}
for &(u, v, w) in edges.iter() {
if dist[u] != [3] && dist[u] + w < dist[v] {
return (dist, true);
}
}
(dist, false)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using usize::MAX for distances when weights are i32 causing type mismatch.
Using i32::MIN which is the smallest integer, not infinity.
✗ Incorrect
Distances are initialized with i32::MAX to represent infinity. The checks compare dist[u] with i32::MAX to avoid overflow and detect negative cycles.
