Java深度首先搜索无限循环

时间:2012-10-25 15:23:17

标签: java infinite-loop depth-first-search

我正在尝试用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 个答案:

答案 0 :(得分:5)

如果图表有循环(或未定向),则必须在访问后标记“节点”,否则您将继续回复它们。

答案 1 :(得分:3)

除非您的图表是树,否则它将具有周期。节点可以是它自己的孙子。您需要阻止已经访问过的节点添加到搜索树中。

一种简单的方法是通过另一种数据结构:

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

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

答案 2 :(得分:0)

如果您的图表包含任何周期,则这是预期的行为;简单深度优先搜索将访问已经访问过的孩子,无限循环。

避免它的一种简单方法是在检查它是否是您正在寻找的节点之后将每个节点添加到HashSet,然后如果已经检查过,则拒绝将其添加到堆栈中。

相关问题