Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. var Graph = {
  2. nodes: {},
  3. queue: [],
  4.  
  5. traverse: function(id) {
  6. if (this.nodes[id].status === 2) return;
  7. this.nodes[id].status = 2;
  8. for ( var i in this.nodes[id].adj ) {
  9. var adjId = this.nodes[id].adj[i];
  10. var adjDist = this.nodes[id].dist[i];
  11. if ((adjDist + this.nodes[id].shortest) < this.nodes[adjId].shortest) {
  12. this.nodes[adjId].shortest = adjDist + this.nodes[id].shortest;
  13. this.nodes[adjId].prev = id;
  14. }
  15. if (this.nodes[adjId].status === 0) {
  16. this.queue.push(adjId);
  17. this.nodes[adjId].status = 1;
  18. }
  19. }
  20. },
  21.  
  22. addNode: function(id, adj, dist) {
  23. this.nodes[id] = {
  24. adj: adj,
  25. dist: dist,
  26. status: 0,
  27. prev: null,
  28. shortest: 10000
  29. };
  30. },
  31.  
  32. init: function() {
  33. this.nodes[1].shortest = 0;
  34. this.nodes[1].status = 1;
  35. this.queue.push(1);
  36. }
  37. };
  38.  
  39. Graph.addNode(1, [2,3,6],[7,9,14]);
  40. Graph.addNode(2, [1,3,4],[7,10,15]);
  41. Graph.addNode(3, [1,2,4,6],[9,10,11,2]);
  42. Graph.addNode(4, [2,3,5],[15,11,6]);
  43. Graph.addNode(5, [4,6],[6,9]);
  44. Graph.addNode(6, [1,3,5],[14,2,9]);
  45.  
  46. function dijkstra() {
  47. Graph.init();
  48. while(Graph.queue.length > 0) {
  49. Graph.traverse(Graph.queue.splice(0,1));
  50. }
  51. console.log(Graph);
  52. }
  53.  
  54. dijkstra();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement