CodeBlanks Logo Icon CodeBlanks

Summary - Bellman-Ford

Run Bellman-Ford and print distances in a mini task.

Summary - Bellman-Ford

In this group you learned Bellman-Ford, which supports negative weights. Edge list, edge loop and negative cycle check combine into the solution.

Now you will write a check function that brings all pieces together. This summary unites the group's concepts in a single piece of code.

Practice has_negative_cycle function

Write has_negative_cycle(edges, n, src). Run Bellman-Ford, do one extra pass and return True if any edge still relaxes. Print True with print(has_negative_cycle([(0, 1, 1), (1, 2, -1), (2, 0, -1)], 3, 0)).

Starter code

solution.py
def has_negative_cycle(edges, n, src):
    # Check if a negative cycle exists

Sample solution

solution.py
def has_negative_cycle(edges, n, src):
    # Check if a negative cycle exists
    dist = [float('inf')] * n
    dist[src] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            return True
    return False
print(has_negative_cycle([(0, 1, 1), (1, 2, -1), (2, 0, -1)], 3, 0))

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is Bellman-Ford's output valid?

  • No negative edges
  • Graph undirected
  • All edges positive
  • No negative cycle Correct answer

Explanation: The output is valid if no negative cycle exists.

2 Negative cycle condition

Question
if dist[u] + w ____ dist[v]: return True
Answer
if dist[u] + w < dist[v]: return True

Explanation: < is right.

3 Summary - Bellman-Ford: match the terms

Term Meaning
init_edges Edges
relax Relaxation
bellman_ford Algorithm
n-1 Passes

All lessons in Advanced