JavaScript 中的最短路径算法
在图论中,最短路径问题是指在图中找到两个顶点(或节点)之间的一条路径,使得构成它的边的权重总和最小。这里我们需修改添加边和添加定向方法,以允许在边中添加权重。
让我们看看如何添加 −
示例
/**
* Adds 2 edges with the same weight in either direction
*
* weight
* node1 <================> node2
* weight
*
*/
addEdge(node1, node2, weight = 1) {
this.edges[node1].push({ node: node2, weight: weight });
this.edges[node2].push({ node: node1, weight: weight });
}
/**
* Add the following edge:
*
* weight
* node1 ----------------> node2
*
*/
addDirectedEdge(node1, node2, weight = 1) {
this.edges[node1].push({ node: node2, weight: weight });
}
display() {
let graph = "";
this.nodes.forEach(node => {
graph += node + "->" + this.edges[node].map(n => n.node) .join(", ")+ "
";
});
console.log(graph);
}现在,在向图中添加边时,如果没有指定权重,则会将默认权重 1 赋予该边。我们现在可以使用它来实现最短路径算法。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP