Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bellman-Ford Algorithm #5

Open
box-lin opened this issue Jun 28, 2023 · 0 comments
Open

Bellman-Ford Algorithm #5

box-lin opened this issue Jun 28, 2023 · 0 comments

Comments

@box-lin
Copy link
Owner

box-lin commented Jun 28, 2023

Bellman-Ford algorithm is a single-source shortest path algorithm, so when you have negative edge weight then it can detect negative cycles in a graph. The only difference between the two is that Bellman-Ford is also capable of handling negative weights whereas Dijkstra Algorithm can only handle positives.

Bellman-Ford Algorithm

  • For a start node, relax each edge for V -1 times. Relaxation is defined as if d[u] + c(u,v) < d[v] then d[v] = d[u] + c(u,v).
  • Time: O(EV)
  • Space: O(V)
d = [math.inf] * len(V)
d[start] = 0
for i in [0, V-1]:
   for u,v in edges:
       # Relaxation
       if d[u] + c(u,v) < d[v]:
             d[v] = d[u] + c(u,v)

# detect for negative cycle
for i in [0, V-1]:
   for u,v in edges:
       # Relaxation
       if d[u] + c(u,v) < d[v]:
             # has a negative cycle
             d[v] = -math.inf  

Problems that can be solve by Bellman-Ford Algorithm

@box-lin box-lin added this to the Graph Algorithm milestone Jun 28, 2023
@box-lin box-lin changed the title Shortest Path Algorithms Bellman-Ford Algorithm Jun 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant