Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Graph = {
- nodes: {},
- queue: [],
- traverse: function(id) {
- if (this.nodes[id].status === 2) return;
- this.nodes[id].status = 2;
- for ( var i in this.nodes[id].adj ) {
- var adjId = this.nodes[id].adj[i];
- var adjDist = this.nodes[id].dist[i];
- if ((adjDist + this.nodes[id].shortest) < this.nodes[adjId].shortest) {
- this.nodes[adjId].shortest = adjDist + this.nodes[id].shortest;
- this.nodes[adjId].prev = id;
- }
- if (this.nodes[adjId].status === 0) {
- this.queue.push(adjId);
- this.nodes[adjId].status = 1;
- }
- }
- },
- addNode: function(id, adj, dist) {
- this.nodes[id] = {
- adj: adj,
- dist: dist,
- status: 0,
- prev: null,
- shortest: 10000
- };
- },
- init: function() {
- this.nodes[1].shortest = 0;
- this.nodes[1].status = 1;
- this.queue.push(1);
- }
- };
- Graph.addNode(1, [2,3,6],[7,9,14]);
- Graph.addNode(2, [1,3,4],[7,10,15]);
- Graph.addNode(3, [1,2,4,6],[9,10,11,2]);
- Graph.addNode(4, [2,3,5],[15,11,6]);
- Graph.addNode(5, [4,6],[6,9]);
- Graph.addNode(6, [1,3,5],[14,2,9]);
- function dijkstra() {
- Graph.init();
- while(Graph.queue.length > 0) {
- Graph.traverse(Graph.queue.splice(0,1));
- }
- console.log(Graph);
- }
- dijkstra();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement