NodeJs语言实现最短路径算法(Shortest Path)
在Node.js中实现最短路径算法,可以使用Dijkstra算法。以下是一个使用Dijkstra算法来计算图中单源最短路径的示例:
class PriorityQueue {
constructor() {
this.collection = [];
}
enqueue(element) {
if (this.isEmpty()) {
this.collection.push(element);
} else {
let added = false;
for (let i = 0; i < this.collection.length; i++) {
if (element[1] < this.collection[i][1]) { // checking priorities
this.collection.splice(i, 0, element);
added = true;
break;
}
}
if (!added) {
this.collection.push(element);
}
}
}
dequeue() {
return this.collection.shift();
}
isEmpty() {
return (this.collection.length === 0);
}
}
class Graph {
constructor(vertices) {
this.vertices = vertices;
this.adjacencyList = new Map();
}
addVertex(vertex) {
this.adjacencyList.set(vertex, []);
}
addEdge(source, target, weight) {
this.adjacencyList.get(source).push({ node: target, weight: weight });
this.adjacencyList.get(target).push({ node: source, weight: weight }); // 如果是有向图,则去掉这一行
}
dijkstra(startVertex) {
let distances = {};
let pq = new PriorityQueue();
let previous = {};
this.adjacencyList.forEach((_, vertex) => {
distances[vertex] = Infinity;
previous[vertex] = null;
});
distances[startVertex] = 0;
pq.enqueue([startVertex, 0]);
while (!pq.isEmpty()) {
let [currentVertex, currentDistance] = pq.dequeue();
this.adjacencyList.get(currentVertex).forEach(neighbor => {
let distance = currentDistance + neighbor.weight;
if (distance < distances[neighbor.node]) {
distances[neighbor.node] = distance;
previous[neighbor.node] = currentVertex;
pq.enqueue([neighbor.node, distance]);
}
});
}
this.printShortestPaths(startVertex, distances);
}
printShortestPaths(startVertex, distances) {
console.log(`Vertex\tDistance from Source ${startVertex}`);
for (let vertex in distances) {
console.log(`${vertex}\t\t${distances[vertex]}`);
}
}
}
// 示例使用
let graph = new Graph(6);
['A', 'B', 'C', 'D', 'E', 'F'].forEach(vertex => graph.addVertex(vertex));
graph.addEdge('A', 'B', 4);
graph.addEdge('A', 'C', 3);
graph.addEdge('B', 'C', 1);
graph.addEdge('B', 'D', 2);
graph.addEdge('C', 'D', 4);
graph.addEdge('D', 'E', 2);
graph.addEdge('E', 'F', 6);
graph.dijkstra('A');
在这个示例中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们从顶点'A'开始运行Dijkstra算法,计算并打印出从顶点'A'到所有其他顶点的最短路径距离。代码使用了自定义的PriorityQueue
类来实现优先队列,以确保每次都选择距离最短的顶点进行处理。