用Java语言实现Dijkstra

时间:2019-04-01 23:11:39

标签: javascript dijkstra

我试图在JavaScript中实现Dijkstra算法的实现以使其正常运行。

我找到了一个演练Here,但不了解返回线

return `Path is ${path} and time is ${times[endNode]}

我已从下面的链接中收集了代码,以使其更加容易。

class Graph {
  constructor() {
    this.nodes = [];
    this.adjacencyList = [];
  }

 addNode(node) {
    this.nodes.push(node); 
    this.adjacencyList[node] = [];
  }
 addEdge(node1, node2, weight) {
    this.adjacencyList[node1].push({node:node2, weight: weight});
    this.adjacencyList[node2].push({node:node1, weight: weight});
  }
findPathWithDijkstra(startNode, endNode) {
  let times = [];
  let backtrace = [];
  let pq = new PriorityQueue();
  times[startNode] = 0;
  
  this.nodes.forEach(node => {
    if (node !== startNode) {
      times[node] = Infinity
    }
  });
  pq.enqueue([startNode, 0]);
    while (!pq.isEmpty()) {
    let shortestStep = pq.dequeue();
    let currentNode = shortestStep[0];

    this.adjacencyList[currentNode].forEach(neighbor => {
      let time = times[currentNode] + neighbor.weight;
		   if (time < times[neighbor.node]) {
        times[neighbor.node] = time;
        backtrace[neighbor.node] = currentNode;
        pq.enqueue([neighbor.node, time]);
      }
    });
  }
  let path = [endNode];
  let lastStep = endNode;

  while(lastStep !== startNode) {
    path.unshift(backtrace[lastStep])
    lastStep = backtrace[lastStep]
  }

  return `Path is ${path} and time is ${times[endNode] }`
	}
}
class PriorityQueue {
  constructor() {
    this.collection = [];
  }
   enqueue(element){
    if (this.isEmpty()){ 
      this.collection.push(element);
    } else {
      let added = false;
      for (let i = 1; i <= this.collection.length; i++){
        if (element[1] < this.collection[i-1][1]){ 
          this.collection.splice(i-1, 0, element);
          added = true;
          break;
        }
      }
      if (!added){
          this.collection.push(element);
      }
    }
  };
    dequeue() {
    let value = this.collection.shift();
    return value;
  };

  isEmpty() {
    return (this.collection.length === 0) 
  };
}

  
let testGraph01 = new Graph();
let testGraph02 = new Graph();
let testGraph03 = new Graph();
//creating graphs
testGraph01.addNode("A");
testGraph01.addNode("B"); 
testGraph01.addNode("C");
testGraph01.addNode("D");

testGraph01.addEdge("A","B",10);
testGraph01.addEdge("C","D",5);
testGraph01.addEdge("D","B",5);


console.log(testGraph01.findPathWithDijkstra("A","D"));

我正在寻找模板化收益的说明。我猜它如何在javascript中工作?

0 个答案:

没有答案