【问题标题】:How to get shortest path between two nodes with Breadth First Search?如何使用广度优先搜索获得两个节点之间的最短路径?
【发布时间】:2020-08-05 05:27:15
【问题描述】:

我正在复习我的算法和数据结构知识,想知道是否有人可以帮助我找出如何使用BFS 找到两个节点之间的最短路径。 到目前为止,我有以下方法,它返回图中最短的部分:

private Node[] nodes;

public static int[] shortestPath(Node source){
        LinkedList<Node> queue = new LinkedList<Node>();
        queue.add(source);

        int[] distances = new int[totalNodes];
        Arrays.fill(distances,-1);

        distances[source] = 0;

        while(!queue.isEmpty()){
            Node node = queue.poll();

            for (int neighbor: nodes[node].neighbor) {
                if(distances[neighbor] == -1) {
                    distances[neighbor] += distances[distanceIndex] + 1;
                    queue.add(neighbor);
                }

            }
        }
            return distances;
    }


}

我想知道如果我想实现这样的方法,解决方案会是什么样子:

public static int[] shortestPath(Node source, Node destination){
// 
}

提前感谢您的帮助,我是数据结构的新手,不知道如何去做

【问题讨论】:

  • 只是函数存根似乎相当广泛。您实际上已经编写了 BFS,为什么不尝试将它移到该函数存根中呢?当您到达目的地时停止循环并使用“来自”哈希图重建路径。有很多骗子可用,here's one

标签: java algorithm data-structures breadth-first-search


【解决方案1】:
private Node[] nodes;

public static int shortestPath(Node source, Node destination){
        LinkedList<Node> queue = new LinkedList<Node>();
        queue.add(source);

        int[] distances = new int[totalNodes];
        Arrays.fill(distances,-1);

        distances[source] = 0;

        while(!queue.isEmpty()){
            Node node = queue.poll();

            for (int neighbor: nodes[node].neighbor) {
                if(distances[neighbor] == -1) {
                    distances[neighbor] += distances[node] + 1;
                    queue.add(neighbor);

                    if(neighbor == destination)
                      break;
                }

            }
        }
            return distances[destination];
    }

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多