Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: DFS in Graphs

  1. #1
    Junior Member
    Join Date
    Apr 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default DFS in Graphs

    This is the implementation of DFS using stacks, but when I try to run this it gives an infinite loop at the first vertex. Graph class has a array of nodes as it's attribute. The node class is used for both Vertices and Edges. I've tested whether the graph is read in correctly or not and it has been. I could provide the input file and the readFile method used to generate the graph. I don't know why it gets stuck in an infinite loop here.
    public static void dfs(Node start)
    {
    //DFS uses Stack data structure
    Stack s=new Stack();
    s.push(start);
    start.visited=true;
    System.out.println(start.item);
    while(!s.isEmpty())
    {
        Node n= (Node)s.peek();
                Node child=getUnvisitedChildNode(n);
        if(child!=null)
        {
            child.visited=true;
            System.out.println(child.item);
            s.push(child);
        }
     
        else
        {
            s.pop();
        }
    }
     
    }
     
    public static Node getUnvisitedChildNode(Node n){
    Node missing_child = new Node();
    Node counter = new Node(n.item);
    while(counter!=null){
         if (!counter.visited)
             missing_child = counter;
    counter = counter.next;
     
    }
     
     
    return missing_child;
    }
    Last edited by antislayer; April 24th, 2011 at 10:35 AM.


  2. #2
    Member
    Join Date
    Feb 2011
    Posts
    55
    My Mood
    Tolerant
    Thanks
    1
    Thanked 16 Times in 15 Posts

    Default Re: DFS in Graphs

    I think I see a problem in getUnvisitedChildNode(), Is it possible for it to return a null value?

  3. #3
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,099
    Thanks
    169
    Thanked 779 Times in 725 Posts
    Blog Entries
    5

    Default Re: DFS in Graphs

    Agree with JJeng. If getUnvisitedChildNode() never returns null, the code in dfs will always be adding another node to the stack, thus the while loop checking the stack size will never quit.

Tags for this Thread