【问题标题】:Java depth first search infinite loopJava深度优先搜索无限循环
【发布时间】:2012-10-15 19:59:04
【问题描述】:

我正在尝试在 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;
}

【问题讨论】:

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


    【解决方案1】:

    如果你的图有循环(或者是无向的),你必须在访问它们之后“标记”节点,否则你会不断地回到它们。

    【讨论】:

      【解决方案2】:

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

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

      Set<Node> visitedNodes = new HashSet<Node>();
      
      //...
      if ( !visitedNodes.contains(children[i]) ) {
         stack.push(children[i]);
         visitedNodes.add(children[i]);
      }
      

      【讨论】:

        【解决方案3】:

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

        避免这种情况的直接方法是在检查每个节点是否是您要查找的节点后将其添加到 HashSet,然后如果已检查过则拒绝将其添加到堆栈中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-31
          • 1970-01-01
          相关资源
          最近更新 更多