java - 如何通过图的广度优先搜索获取路径中的所有节点

标签 java graph-theory breadth-first-search

假设我们有一个像这样的简单图表:

enter image description here

使用深度优先搜索很容易找到从起始节点到结束节点的路径,但在尝试使用广度优先搜索做同样的事情时我陷入了困境。我的代码如下:

public List<String> getPathBreadth(String name1, String name2) {
    Node node1 = getNode(name1);
    Node node2 = getNode(name2);
    if (node1 == null || node2 == null) {
        return null;
    }
    return getPathBreadth(node1, node2, new HashSet<String>(), new LinkedList<Node>());
}

private List<String> getPathBreadth(Node start, Node destination, HashSet<String> visited, Queue<Node> queue) {
    List<String> path = new ArrayList<String>();
    if (start == destination) {
        path.add(start.name);
        return path;
    }
    visited.add(start.name);
    queue.offer(start);
    while (queue.size() > 0) {
        Node cur = queue.poll();
        for (String friend : cur.friends) {
            if (visited.contains(friend)) {
                continue;
            }
            visited.add(friend);
            if (getNode(friend) == destination) {
                path.add(friend); // I got the final node, I could also add cur, but how do I get the previous nodes along the path
                return path;
            }
            queue.offer(getNode(friend));
        }
    }
    return path;
}

假设我们想要从 JohnLinda,所以我希望返回类似 [Linda, Robert, John][Linda, Patrica, John] 的东西,但我现在能做的最好的就是获取最后一个和倒数第二个节点。在本例中,他们是 LindaRobert。如何获取路径上所有先前的节点?

最佳答案

为了使代码可用,请添加Node定义和树(测试数据)。 (参见mcve)。
我认为问题出在这里:

if (getNode(friend) == destination) {
                path.add(friend); 
                return path;
 }

您添加到最后一个路径的唯一节点。尝试:

path.add(friend);     
if (getNode(friend) == destination) {                
     return path; //or better: break;
}

不幸的是,我无法运行并检查它。

附注:
visited.add(friend) 如果此集合尚未包含friend,则返回 true
所以:

if (visited.contains(friend)) {
   continue;
}
visited.add(friend);

可以替换为

 if (! visited.add(friend)) {
     continue;
 }

关于java - 如何通过图的广度优先搜索获取路径中的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50476672/

相关文章:

java - 使用 Java 从页面中的表中获取数据

java - 线程如何从运行状态转变为可运行状态?

graph-theory - 每个节点都连接到每个其他节点的图如何表示?

algorithm - 删除一些边后的DFS

algorithm - 哪种数据结构最适合代表三人棋盘?

java - SurfaceView同时显示两个动画

java - Spring MVC Controller 测试 - 打印结果 JSON 字符串

C++ STL 广度优先搜索

c++ - 广度优先搜索的效率

time-complexity - dfs 还是 bfs 更适合在有向图上测试二部?