我是一名前端Javascript開發人員,但想學習一些圖論以準備Google面試,我查閱了Dijkstra算法的一些實現。Dijkstra的算法應該返回什麼?
的例子這裏列出 https://github.com/mburst/dijkstras-algorithm/blob/master/dijkstras.js 似乎適合於尋找兩個節點之間的最短路徑,並返回它們之間的最短節點路徑,但在維基百科上的僞代碼版本似乎同時返回「上一個,和DIST」 - - 他們應該是什麼?
我試圖修改GitHub的例子,以配合維基百科僞和返回的距離似乎給最短的數值距離分別來自startVertex ...但上一個沒有返回的最短路徑
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 }
此實現似乎的最短路徑的長度從給定的節點返回到每一個節點,在這種情況下'S'。 – mrmcgreg
根據你的需要,它可以返回路徑和/或路徑中所有頂點的總和。 – Mox
什麼是prev應該在wikipedia pseudocode? – WinchenzoMagnifico