Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java depth first search infinite loop

I'm trying to implement a depth first search algorithm in Java. Any idea why this method is going into an infinite loop? Thanks.

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;
}
like image 952
James Avatar asked Feb 18 '23 17:02

James


2 Answers

If you graph has cycles (or is undirected), you must "mark" the nodes after you visit them, otherwise you will keep coming back to them.

like image 71
pedrosorio Avatar answered Feb 28 '23 09:02

pedrosorio


Unless your graph is a tree, it will have cycles. A node can be its own grandchild. You need to prevent nodes you've already visited from being added to the search tree.

A simple way to do this is through another data structure:

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

//...
if ( !visitedNodes.contains(children[i]) ) {
   stack.push(children[i]);
   visitedNodes.add(children[i]);
}
like image 41
Mark Peters Avatar answered Feb 28 '23 09:02

Mark Peters