Dijkstra的算法应该返回什么
What is Dijkstra's algorithm supposed to return?
我是一名前端Javascript开发人员,但想学习一些图论来准备Google面试,我查找了Dijkstra算法的一些实现。
此处列出的示例https://github.com/mburst/dijkstras-algorithm/blob/master/dijkstras.js似乎适合找到两个节点之间的最短路径并返回它们之间的最短节点路径,但维基百科上的伪代码版本似乎同时返回"prev和dist"---它们应该是什么?
我尝试修改 github 示例以匹配维基百科伪代码,返回距离似乎确实从一开始就为每个示例提供了最短的数字距离顶点...但是 Prev 没有返回最短路径
var INFINITY = 1/0;
function PriorityQueue () {
this._nodes = [];
this.enqueue = function (priority, key) {
this._nodes.push({key: key, priority: priority });
this.sort();
}
this.dequeue = function () {
return this._nodes.shift().key;
}
this.sort = function () {
this._nodes.sort(function (a, b) {
return a.priority - b.priority;
});
}
this.isEmpty = function () {
return !this._nodes.length;
}
}
function Graph(){
this.vertices = {};
this.addVertex = function(name, edges){
edges = edges || null;
this.vertices[name] = edges;
}
}
function djikstra(graph, startVertex) {
var nodes = new PriorityQueue();
var distances = {};
var previous = {};
for(vertex in graph.vertices) {
if (vertex === startVertex) {
distances[vertex] = 0;
nodes.enqueue(0, vertex);
} else {
distances[vertex] = INFINITY;
nodes.enqueue(INFINITY, vertex);
}
previous[vertex] = null;
}
while(!nodes.isEmpty()) {
var smallest = nodes.dequeue();
for(var neighbor in graph.vertices[smallest]) {
var alt = distances[smallest] + graph.vertices[smallest][neighbor];
if(alt < distances[neighbor]) {
distances[neighbor] = alt;
previous[neighbor] = smallest;
}
}
}
return distances;
}
var graph = new Graph();
graph.addVertex('S', {V: 1, W: 4});
graph.addVertex('V', {W: 2, T: 6});
graph.addVertex('W', {T: 3});
graph.addVertex('T');
console.log(djikstra(graph, 'S'));
//
{ S: 0, V: 1, W: 3, T: 6 }
Dijkstra 算法是一种算法,它为您提供从某个点到所有其他点的最短距离,以获得非负图。
有许多不同的修改。您可以返回两个节点之间的距离、一个节点与所有其他节点之间的距离、距离和路径、距离和前一个节点(足以构造路径)。
因此,在维基百科文章的情况下 - 它会返回您到所有顶点的距离以及路径中获取路径的前一个顶点是什么。
附言如果你想准备面试,我建议你停止查看随机的github存储库(可能很难理解特定人员的代码,这可能是错误的/次优的),而是打开一本书,尝试理解算法背后的逻辑。特别是如果算法可以用 50 行<编写。>
相关文章:
- 它将返回什么新日期(DateObject)
- 如果statusCode不是200,那么从http调用返回什么类型的错误对象
- Dijkstra的算法应该返回什么
- 具有多个返回语句的函数返回什么
- 如果未找到搜索方法,则应返回什么
- 如果字符串不匹配,.split() 返回什么
- querySelectorAll 和 getElementsBy* 方法返回什么
- 获取 0 的文档元素返回什么
- unescape()函数返回什么
- 我的函数应该通过.fail()回调为Ajax请求返回什么
- backbonejs入门-服务器应该返回什么
- 当index=-1时,JS在请求myArray[index]时返回什么
- 如果在已经是最后一个元素上调用jQuery.next方法,那么它会返回什么
- 从父函数返回什么以获取从子函数/嵌套函数返回的值
- getCurrentPosition返回什么
- 以下Javascript语句返回什么以及为什么返回
- String.charAt() 在给定一个无法解析为 int 的字符串的情况下返回什么
- 递归闭包返回什么?
- 对于非异步路径返回什么
- 在等待$onInit回调完成时,我应该为Angular绑定的属性返回什么?