迭代DFS查找从源到目标的路径

时间:2017-03-25 20:26:36

标签: java algorithm graph-theory

我很感激帮助调试我的DFS实现以找到路径。我的实现通常运行良好,但在某个边缘情况下,会为算法访问的结果添加一个额外的节点,但不应包含在解决方案中,因为从它到结果列表中的下一个节点的路径不存在。问题可能是由R​​esult.add(nextNode)的位置引起的,但我无法修复此错误。

下面附有一个问题的例子(任意权重),因此算法返回[0 2 4 1 3 5],即使没有从4到1的边缘。

Example

有人可以建议如何修改我的代码,以便像这样的节点没有添加到结果中吗?

 public static ArrayList<Integer> pathDFS(Integer source, Integer destination, WeightedGraph graph) {
            ArrayList<Integer> Result = new ArrayList<Integer>();
            ArrayList<Integer> Visited = new ArrayList<Integer>();
            Stack<Integer> s = new Stack<>();
            s.push(source);
            Visited.add(source);
            while (!s.isEmpty()) {
                Integer v = s.pop();
                    for (int nextNode : getAdjacentNodes(v, graph)) {
                        if (!Visited.contains(nextNode)) {
                            s.push(nextNode);
                            Visited.add(nextNode);
                            **Result.add(nextNode);**
                            if (nextNode == destination)
                                return Result;
                    }
                }
            }
            return Result;
        }

1 个答案:

答案 0 :(得分:1)

每次将节点添加到result列表时,将节点添加到visited列表显然是错误的(访问节点集不一定只包含路径。它可以有一堆其他节点节点,而不仅仅是一个节点。

要修复它,您可以创建一个parent列表来存储每个节点的父节点(并在发现新节点时填充它)。这样,您只需要通过父链接从目标节点转到源来重建路径。