Java深度优先搜索无限循环

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

最佳答案

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

关于Java深度优先搜索无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071909/

相关文章:

java - 如何在 Google 日历 java API 中使用 FreeBusyResponse?

c - 我的字符频率程序似乎有一个无限循环

java - 使用迭代器的无限循环

stack - 我如何记住 DFS 和 BFS 使用哪些数据结构?

java - run方法后执行代码?

java - 在这种情况下,同步块(synchronized block)会帮助我吗?

java - 使用 DFS 解决 8 谜游戏

recursion - 返回最小生成树中两个节点之间的路径

Java:如何从集合中获取n个元素

unit-testing - 如何对某些输入陷入无限循环的方法进行单元测试?