什么是Dijkstra的算法应该返回?

时间:2016-03-06 02:53:38

标签: javascript algorithm dijkstra

我是一名前端Javascript开发人员,但想要学习一些图形理论来准备Google面试,我查看了Dijkstra算法的一些实现。

此处列出的示例 https://github.com/mburst/dijkstras-algorithm/blob/master/dijkstras.js 似乎适合找到两个节点之间的最短路径并返回它们之间的最短节点路径,但维基百科上的伪代码版本似乎同时返回" prev和dist" ---它们应该是什么是?

我尝试修改github示例以匹配wikipedia伪代码,并且返回距离确实给出了来自startVertex的每个最短的数值距离...但是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 }

1 个答案:

答案 0 :(得分:3)

Dijkstra算法是一种算法,它为您提供从某个点到非负图的所有其他点的最短距离。

有许多不同的修改。您可以返回两个节点之间的距离,节点与所有其他节点之间的距离,距离和路径,距离以及前一个节点(足以构建路径)。

因此,在维基百科文章的情况下,它会返回到所有顶点的距离以及路径中前一个顶点以获取路径。

PS 如果您想准备面试,我建议您停止查看随机github repos(可能很难理解某个人的代码,这可能是错误的/次优),而是打开一本书,试着理解算法背后的逻辑。特别是如果算法可以用&lt; 50行。