Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. function BellmanFord(list vertices, list edges, vertex source)
  2. ::distance[],predecessor[]
  3.  
  4. // This implementation takes in a graph, represented as
  5. // lists of vertices and edges, and fills two arrays
  6. // (distance and predecessor) about the shortest path
  7. // from the source to each vertex
  8.  
  9. // Step 1: initialize graph
  10. for each vertex v in vertices:
  11. distance[v] := inf // Initialize the distance to all vertices to infinity
  12. predecessor[v] := null // And having a null predecessor
  13.  
  14. distance[source] := 0 // The distance from the source to itself is, of course, zero
  15.  
  16. // Step 2: relax edges repeatedly
  17. for i from 1 to size(vertices)-1:
  18. for each edge (u, v) with weight w in edges:
  19. if distance[u] + w < distance[v]:
  20. distance[v] := distance[u] + w
  21. predecessor[v] := u
  22.  
  23. // Step 3: check for negative-weight cycles
  24. for each edge (u, v) with weight w in edges:
  25. if distance[u] + w < distance[v]:
  26. error "Graph contains a negative-weight cycle"
  27.  
  28. return distance[], predecessor[]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement