Java深度优先搜索无限循环。

4

我正在尝试在Java中实现深度优先搜索算法。 有任何想法为什么这个方法会进入无限循环?谢谢。

public Node search(Graph graph, String nodeName, int ID) {

    //Get the root node
    Node root = graph.getRoot();

    Stack<Node> stack = new Stack<Node>();
    //Add the root to the stack
    stack.push(root);

    while(!stack.isEmpty()) 
    {
        Node n = stack.pop();
        //Check to see if node n is the requested node
        if(n.getName().equals(nodeName))
        {
            //Found
            return n;
        }else
        {
            //Create an array of the leaf nodes to node n
            Node[] children = n.getNeighbours();
            for(int i =0; i<children.length; i++)
            {
                //Add the leaf nodes to the stack
                stack.push(children[i]);
                System.out.println(stack.peek());
            }
        }
    }
    //Not found so return null
    return null;
}
3个回答

5
如果你的图有环(或是无向图),你必须在访问节点后“标记”它们,否则你会一直回到它们那里。

3

除非您的图是一棵树,否则它将具有循环。节点可以是其自身的孙子。您需要防止将已访问过的节点添加到搜索树中。

一个简单的方法是通过另一个数据结构实现:

Set<Node> visitedNodes = new HashSet<Node>();

//...
if ( !visitedNodes.contains(children[i]) ) {
   stack.push(children[i]);
   visitedNodes.add(children[i]);
}

0
如果您的图包含任何循环,这是预期行为;简单的深度优先搜索将访问已经访问过的子节点,无限循环。
避免这种情况的一种简单方法是,在检查它是否为您要查找的节点后,将每个节点添加到 HashSet 中,然后拒绝将其添加到堆栈中,如果它已经被检查过。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接