1

I'm trying to figure out how I can calculate the shortest path within many nodes to a root node, but i have no clue how to do it the right way. The Nodes are somehow connected to each other, so there are always multiple paths to the root node.

I have a js object with all nodes, here is a snippet if it:

var nodes = {
11420 : {       // no out, but many other nodes have 11420 in their out
    out : []
},
18866 : {
    out : [11420]
},
739 : {
    out : [18866]
},
1957 : {
    out : [739]
},
33296 : {
    out : [1957, 36774]
},
57264 : {
    out : [33296]
},
54447 : {       // root
    out : [57264]
},
37569 : {
    out : [36542, 57264]
}
// ... 1500 nodes more

}

How can I calculate the shortest Path for lets say Node 11420 to root 54447? The result should be an array with the node ids.

Thank you.

eScoo
  • 151
  • 3
  • 14
  • Possible duplicate of [Shortest path in JavaScript](http://stackoverflow.com/questions/32527026/shortest-path-in-javascript) – Mike Cluck Oct 04 '15 at 22:27

2 Answers2

3

Demo in the demo there is a minified Code it's this :https://raw.githubusercontent.com/andrewhayward/dijkstra/master/graph.js

var nodes = 
{
    "11420" : 
    {    
        "18866":1               
    },
    "18866" :
    {
        "11420":1,
        "739":1             
    },
    "739" : 
    {
        "18866":1,
        "1957":1                
    },
    "1957" : 
    {
        "739":1 ,
        "33296":1
    },
    "33296" :
    {
        "1957":1,
        "36774":1,
        "57264":1
    },
    "57264" : 
    {
        "33296":1,
        "54447" :1
    },
    "54447" : 
    {
        "57264":1
    },
    "37569" : 
    {
        "36542":1,
        "57264":1
    }
};

var graph = new Graph(nodes);
var result = graph.findShortestPath('11420', '54447');
console.log(result);

$("#yoo").html("["+result.join()+"]"); 
Diptox
  • 1,809
  • 10
  • 19
1

Read up on Djikstra's Algorithm for finding the shortest path through nodes in a graph. This page seems to have a good description. The general algorithm is based on weighted graphs (if two nodes are connected there is a "weight" or "cost" associated with traversing the edge between the nodes); in your case, you can assume each weight is 1.

keithmo
  • 4,893
  • 1
  • 21
  • 17