Dijkstra的算法应该返回什么

What is Dijkstra's algorithm supposed to return?

本文关键字:返回 什么 算法 Dijkstra      更新时间:2023-09-26

我是一名前端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 行<编写。>