0

The depth first search does not function properly. Honestly I am not sure if this is the current way of implementation. I am new to implementing graph and want to be a pro at it. Where am I going wrong and I do not understand how do I print the elements either in the dfs() function so I can know how dfs should be like.

Would getter & setter method for child elements is recommended?

Here is my code:

    package graphs;

    public enum State {

        Unvisited,Visiting,Visited;

    }

    package graphs;

    public class Node {

        public Node[] adjacent;
        public int adjacentCount;
        private String vertex;
        public graphs.State state;

        public Node(String vertex)
        {
            this.vertex = vertex;
        }
        public Node(String vertex, int adjacentlen)
        {
            this.vertex = vertex;
            adjacentCount = 0;
            adjacent = new Node[adjacentlen];
        }

        public void addAdjacent(Node adj)
        {
            if(adjacentCount < 30)
            {
                this.adjacent[adjacentCount] = adj;
                adjacentCount++;
            }
        }

        public Node[] getAdjacent()
        {
            return adjacent;

        }

        public String getVertex()
        {
            return vertex;
        }

    }

    public class Graph {

        public int count; // num of vertices
        private Node vertices[];

        public Graph()
        {
            vertices = new Node[8];
            count = 0;
        }

        public void addNode(Node n)
        {
            if(count < 10)
            {
                vertices[count] = n;
                count++;
            }
            else
            {
                System.out.println("graph full");
            }
        }

        public Node[] getNode()
        {
            return vertices;
        }
    }


    package graphs;

    import java.util.Stack;
    import graphs.State;
    public class Dfs {

        /**
         * @param args
         */

        static boolean visited[];

        public void dfs(Node root)
        {       
            if(root == null) return;

            Stack<Node> s = new Stack<Node>();
            s.push(root);
            root.state = State.Visited;

            System.out.println("root:"+root.getVertex() + "\t");
            while(!s.isEmpty())
            {
                Node u = s.pop();
                for(Node n: u.getAdjacent())
                {

                    if(n.state != State.Visited)
                    {
                        dfs(n);
                    }
                }
            }
        }

        public static Graph createNewGraph()
        {
            Graph g = new Graph();        
            Node[] temp = new Node[8];

            temp[0] = new Node("A", 3);
    temp[1] = new Node("B", 3);
    temp[2] = new Node("C", 1);
    temp[3] = new Node("D", 1);
    temp[4] = new Node("E", 1);
    temp[5] = new Node("F", 1);

    temp[0].addAdjacent(temp[1]);
    temp[0].addAdjacent(temp[2]);
    temp[0].addAdjacent(temp[3]);

    temp[1].addAdjacent(temp[0]);
    temp[1].addAdjacent(temp[4]);
    temp[1].addAdjacent(temp[5]);

    temp[2].addAdjacent(temp[0]);
    temp[3].addAdjacent(temp[0]);
    temp[4].addAdjacent(temp[1]);
    temp[5].addAdjacent(temp[1]);

            for (int i = 0; i < 7; i++) 
            {
                g.addNode(temp[i]);
            }
            return g;
        }

        public static void main(String[] args) {


            Graph g = createNewGraph();
            Dfs s = new Dfs();
            //Node[] n = g.getNode();

            s.dfs(g.getNode()[0]);

        }

    }
1
  • 1
    Pick either recursion or iteration - don't do both (i.e. get rid of the stack and while loop or get rid of the recursive calls). Commented Apr 29, 2014 at 18:52

1 Answer 1

1

You don't need stack here. Only recursion:

public void dfs(Node node) {
    if (node == null) {
        return;
    }

    System.out.println("Node: " + node.getVertex());
    node.state = State.Visited;

    for (Node n : node.getAdjacent()) {
        if (n.state != State.Visited) {
            dfs(n);
        }
    }
}

UPDATE

To check path existence:

public boolean isPath(Graph graph, Node start, Node target) {
    for (Node node : graph.getNode()) {
        if (node != null) {
            node.state = State.Unvisited;
        }
    }

    dfs(start);

    return target.state == State.Visited;
}
Sign up to request clarification or add additional context in comments.

6 Comments

what should the expected output be for the input that I have provided?
Graph traversal output: A B E F C D. A is root node. Print 'A'. We pick up first neighbor B and invoke dfs(B). Print 'B'. Pick up first neighbor A, but A is already visited, pick up next neighbor E and invoke dfs(E). Print 'E'. Pick up first neighbor B, but B is already visited and there are no neighbors anymore so we roll back to node B. Pick up next neighbor F and invoke dfs(F)... And so on. I think you got it :)
thanks I got it :) I tried with simple example and then tested my algorithm with different inputs
can u suggest any unnecessary methods or improvements then plz let me know
Enums replace with Set<Node> and array of adjacent replace with Collection<Node>. Specifically, I can not say, as even my DFS-algorithm you marked as incorrect, so I don't know what you need.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.