javascript - 使用 BFS (javascript) 查找最短路径未加权图

标签 javascript algorithm breadth-first-search

我正在尝试应用 BFS 来查找图中最短路径的长度,但我没有得到完全正确的结果。

我试图通过访问图中的每个节点来找到最短路径;然后标记访问过的,并继续记录路径的长度。我希望返回的是一个包含最短路径的数组,但我认为我在这个过程中做错了什么。

我认为这与我索引数组和记录距离的方式有关。

我的输入当前以数组形式格式化,其中包含每个顶点 i 的邻居。因此,例如,graph[i] 将为您提供顶点 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] + 1imin_node 内边的索引,这一点都不有趣。您要查找的是当前到 min_node 的距离。您需要将距离分配为 min_node 对象本身的属性,或者您需要存储队列中节点的 ID(graph 中的索引)而不是对象本身。

我做了一些其他的简化,但您的代码中唯一的问题是距离查找。

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;
}

关于javascript - 使用 BFS (javascript) 查找最短路径未加权图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52901344/

相关文章:

javascript - 在 IE 的 iframe 中获取选定的文本

javascript - 网页表单未运行脚本

c# - WPF 多边形相交

algorithm - 在图中选择最佳可能的初始位置以最大化潜在邻居

algorithm - 指纹树生成

c++ - 使用迭代深度优先搜索算法的未加权图的最短路径

javascript - 使用ajax在while循环中更新MySql数据库记录 - 仅更新第一行

javascript - 如何使用 Hammer.js 2.0 停止传播()?

c++ - 通过元素原始位置的奇偶校验来稳定分区std::vector

algorithm - 如何在合并排序中控制我的算法的堆栈溢出