0
votes

Graph image

    public void dfs(){
    ArrayList<Node> exploredList = new ArrayList<>();
    Stack s=new Stack();
    s.push(this.rootNode);
    while(!s.isEmpty()){
        Node n = (Node)s.pop();
        exploredList.add(n);
        printNode(n);
        ArrayList<Node> childList = getChildNodes(n);
        for (Node child : childList){
            if (!exploredList.contains(child) && !s.contains(child)) {
                s.push(child);
        }
    }
    }

Output:

A D C F B E 

I am confused with DFS algorithm. The above code adds all child nodes to the stack, removes it from the stack and visits until it reaches the end node, while the other implementation (following reference link) adds one node to the stack, visits until it reaches the end node and backtracks.

Is the above code implementation of the DFS algorithm? If yes? How it is different from other DFS implementations? The output of other DFS algorithm should be:

Output:

A B E F C D 

Reference: Introduction to Graph with Breadth First Search(BFS) and Depth First Search(DFS) Traversal Implemented in JAVA