Java深度首先搜索无限循环

Jam*_*mes 4 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;
}
Run Code Online (Sandbox Code Playgroud)

ped*_*rio 5

如果图形具有周期(或未定向),则必须在访问它们之后"标记"节点,否则您将继续回到它们.