简体   繁体   中英

JavaScript - shortest path through hundreds of nodes in a graph

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.

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()+"]"); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM