如何从图的广度优先搜索中获取路径中的所有节点

时间:2018-05-22 21:25:40

标签: 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;
}

假设我们想要从John转到Linda,所以我希望返回[Linda, Robert, John][Linda, Patrica, John]之类的内容,但我现在能做的最好的事情就是得到最后一个节点和最后一个节点。在这种情况下,它们是LindaRobert。如何获取路径中的所有先前节点?

1 个答案:

答案 0 :(得分:0)

要使代码可用,请添加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)如果此集合尚未包含朋友,则返回true 所以:

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

可以替换为

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