在图论中,最短路径问题是在图中的两个顶点(或节点)之间找到路径的问题,以使其构成边的权重之和最小。在这里,我们需要修改添加边缘并添加有向方法,以允许向边缘添加权重。
让我们看看如何添加它-
/** * 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(", ")+ "\n"; }); console.log(graph); }
现在,当在图上添加一条边时,如果我们不指定权重,则会为该边分配默认权重1。现在,我们可以使用它来实现最短路径算法。