javascript - 使用 BFS (javascript) 查找最短路径未加权图
问题描述
我正在尝试应用 BFS 来查找图中最短路径的长度,但并没有得到正确的结果。
我尝试通过访问图中的每个节点来找到最短路径;然后标记访问过的那些,并继续记录路径的长度。我希望返回的是一个包含最短路径的数组,但我认为我在这个过程中做错了什么。
我认为这与我如何索引我的数组和记录我的距离有关。
我的输入目前以数组的形式格式化,其中包含每个顶点的邻居i
。因此,例如,graph[i]
会给你一个 vertex 的邻居数组i
。
关于如何解决我的问题的任何想法都会非常有帮助。谢谢!
var shortestPathLength = function(graph) {
let distances = []
let pq = []
distances[0] = 0
let mygraph = {}
for (var i = 0; i<graph.length; i++) {
distances[i] = -1
mygraph[i] = graph[i]
}
pq.push(mygraph[0])
while(pq.length > 0) {
let min_node = pq.shift()
for(var i = 0; i<min_node.length; i++) {
candidate = distances[i] + 1
if(distances[min_node[i]]== -1) {
distances[min_node[i]] = distances[i] + 1
pq.push(graph[min_node[i]])
}
else if (candidate < distances[min_node[i]]) {
distances[min_node[i]] = distances[i] + 1
}
}
}
function getSum(total, num) {
return total + num;
}
console.log(distances)
return distances.length
};
解决方案
你的问题是candidate = distances[i] + 1
。是 内边的i
索引min_node
,这一点都不有趣。您正在寻找的是当前到min_node
. 您需要将距离指定为min_node
对象本身的属性,或者您需要将graph
节点的 id(in 中的索引)存储在队列中,而不是对象本身。
我做了一些其他的简化,但你的代码中唯一的问题是距离查找。
function shortestPathLength = function(graph) {
const distances = Array(graph.length).fill(-1);
distances[0] = 0; // start node
const queue = [0];
while (queue.length > 0) {
const node_index = queue.shift();
// ^^^^^
const edges = graph[node_index]; // get the node itself
const candidate = distances[node_index] + 1; // outside of the loop
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
for (const target in edges) {
if (distances[target] == -1) {
distances[target] = candidate;
queue.push(target); // not graph[target]
// ^^^^^^
}
}
}
return distances;
}
推荐阅读
- html - 如何修复css动画中的元素
- deployment - java.lang.IllegalStateException:应用程序部署后 weblogic 12.2 启动期间 zip 文件关闭
- discord.js - 虽然我定义了一个频道,但nodejs说它是未定义的
- angular - 角度读取后响应标题不起作用
- firebird - 包含文本的 Firebird INDEX 表达式。可能吗?
- spring - 匿名用户无法访问允许匿名访问的 url 模式
- php - Timber Twig - 如果日期/时间是过去/现在/未来,则拆分类别帖子
- python - 如何在 Plot Pie Graph 中增大尺寸?
- azure - 不同区域的资源组和资源本身
- laravel - 背景图像未在 dompdf laravel 中显示