如何使用 JavaScript 实现 Dijkstra 算法? - 项越资源网-html css js 用法分享社区-开发交流-项越资源网

如何使用 JavaScript 实现 Dijkstra 算法?

/* 如何使用 JavaScript 实现 Dijkstra 算法? */
function Graph() {
  var vertices = [];
  var adjList = new Dictionary();
  this.addVertex = function(v) {
    vertices.push(v);
    adjList.set(v, []);
  };
  this.addEdge = function(v, w) {
    adjList.get(v).push(w);
    adjList.get(w).push(v);
  };
  this.toString = function() {
    var s = '';
    for (var i = 0; i < vertices.length; i++) {
      s += vertices[i] + ' -> ';
      var neighbors = adjList.get(vertices[i]);
      for (var j = 0; j < neighbors.length; j++) {
        s += neighbors[j] + ' ';
      }
      s += '\n';
    }
    return s;
  };
  var initializeColor = function() {
    var color = [];
    for (var i = 0; i < vertices.length; i++) {
      color[vertices[i]] = 'white';
    }
    return color;
  };
  this.BFS = function(v) {
    var color = initializeColor(),
      queue = new Queue(),
      d = [],
      pred = [];
    queue.enqueue(v);
    for (var i = 0; i < vertices.length; i++) {
      d[vertices[i]] = 0;
      pred[vertices[i]] = null;
    }
    while (!queue.isEmpty()) {
      var u = queue.dequeue(),
        neighbors = adjList.get(u);
      color[u] = 'grey';
      for (i = 0; i < neighbors.length; i++) {
        var w = neighbors[i];
        if (color[w] === 'white') {
          color[w] = 'grey';
          d[w] = d[u] + 1;
          pred[w] = u;
          queue.enqueue(w);
        }
      }
      color[u] = 'black';
    }
    return {
      distances: d,
      predecessors: pred
    };
  };
  var shortestPathAux = function(v, u) {
    var path = [];
    var shortestPathAuxHelper = function(v, u) {
      if (u === v) {
        path.push(v);
      } else if (pred[u] === null) {
        return null;
      } else {
        path.push(u);
        shortestPathAuxHelper(v, pred[u]);
      }
    };
    shortestPathAuxHelper(v, u);
    return path;
  };
  this.shortestPath = function(v, u) {
    var bfsInfo = this.BFS(v);
    var pred = bfsInfo.predecessors,
      path = shortestPathAux(v, u);
    return path;
  };
}
请登录后发表评论

    没有回复内容