Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. /**
  2. Initiate
  3. distance - stores the distance of the shortest path from source to each vertex.
  4. predecessor - for each vertex, predecessor stores its previous vertex on the path from the source to it.
  5. For the object distance, define each property for the corresponding vertex as Infinity, except for the source,
  6. which should be zero. For the object predecessor, set the property for every vertex as null.
  7.  
  8. Cycle
  9. Repeatedly check all the edges to see if the stored distance (total weight from the source to a target vertex)
  10. for side u of the edge plus the edge's weight w is smaller than the distance of another vertex u.
  11. If it is true, set the distance of v as the distance of u plus w; and set predecessor of v as u.
  12. The process repeats with vertices.length times to guarantee the shortest result.
  13.  
  14. Check
  15. Do one more time and throw an error if there exists a negative-weight cycle.
  16. The negative cycle is a problem because it prevents the algorithm from finding the correct answer.
  17. */
  18. export const graph = {
  19. vertices: [ 'A', 'B', 'C', 'D', 'E' ],
  20. edges: [
  21. { u: 'A', v: 'B', w: 4 },
  22. { u: 'A', v: 'C', w: 2 },
  23. { u: 'B', v: 'C', w: 3 },
  24. { u: 'B', v: 'D', w: 2 },
  25. { u: 'B', v: 'E', w: 3 },
  26. { u: 'C', v: 'B', w: 1 },
  27. { u: 'C', v: 'D', w: 4 },
  28. { u: 'C', v: 'E', w: 5 },
  29. { u: 'E', v: 'D', w: -5 }
  30. ],
  31. positions: {
  32. A: { x: 60, y: 180 },
  33. B: { x: 240, y: 60 },
  34. C: { x: 240, y: 300 },
  35. D: { x: 420, y: 60 },
  36. E: { x: 420, y: 300 }
  37. }
  38. };
  39.  
  40. export const bellmanFord = ({ vertices, edges }, source) => {
  41. const distance = vertices.reduce((r, i) => ({ [i]: Infinity, ...r }), { [source]: 0 });
  42. const predecessor = vertices.reduce((r, i) => ({ [i]: null, ...r }), {});
  43.  
  44. vertices.forEach(() => {
  45. edges.forEach(({ u, v, w }) => {
  46. if (distance[v] > distance[u] + w) {
  47. distance[v] = distance[u] + w;
  48. predecessor[v] = u;
  49. }
  50. });
  51. });
  52.  
  53. // check for negative-weight cycles
  54. for (let { u, v, w } of edges) {
  55. if (distance[v] > distance[u] + w) throw 'Graph contains a negative-weight cycle';
  56. }
  57.  
  58. return { distance, predecessor };
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement