
该算法用于计算城市之间的最小最短距离。
连同所附文章,如果您想了解更多信息,我添加了另一个增强功能。
我计算了之前的路径,从那里我们可以得到它到达那里的完整路径。
const dijkstra = (graph) => { const vertex = graph.length; const path = new Array(vertex).fill(false); const distance = new Array(vertex).fill(Infinity); const prev = [-1]; distance[0] = 0; // source Node const getMinDistanceIndex = (path, distance) => { let min = Infinity; let minIndex = -1; for (let j = 0; j distance[j]) { min = distance[j]; minIndex = j; } } return minIndex; } for (let i = 0; i < vertex; i++) { const minDistanceIndex = getMinDistanceIndex(path, distance); path[minDistanceIndex] = true; for (let j = 0; j 0 && distance[minDistanceIndex] + graph[minDistanceIndex][j] < distance[j]) { distance[j] = distance[minDistanceIndex] + graph[minDistanceIndex][j]; prev[j] = minDistanceIndex; } } } console.log(path, distance, prev);}const graph = [ [ 0, 4, 0, 0, 0, 0, 0, 8, 0 ], [ 4, 0, 8, 0, 0, 0, 0, 11, 0 ], [ 0, 8, 0, 7, 0, 4, 0, 0, 2 ], [ 0, 0, 7, 0, 9, 14, 0, 0, 0], [ 0, 0, 0, 9, 0, 10, 0, 0, 0 ], [ 0, 0, 4, 14, 10, 0, 2, 0, 0], [ 0, 0, 0, 0, 0, 2, 0, 1, 6 ], [ 8, 11, 0, 0, 0, 0, 1, 0, 7 ], [ 0, 0, 2, 0, 0, 0, 6, 7, 0 ]];dijkstra(graph);/*[true, true, true, true, true, true, true, true, true][0, 4, 12, 19, 21, 11, 9, 8, 14][-1, 0, 1, 2, 5, 6, 7, 0, 2]*/
如果您有任何疑问,请随时联系我
参考
https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
以上就是使用 Javascript 的 Dijkstra 算法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1490854.html
微信扫一扫
支付宝扫一扫