Search code examples
javagraphdepth-first-searchgraph-traversal

Confused with DFS implementation


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


Solution

  • What makes it a DFS (depth-first search) is the fact that it is traversing the graph by continuously visiting deeper and deeper nodes in the graph before backtracking and visiting other nodes which have been added to the stack. Note: this does not guarantee visiting the nodes in a specified order. Two perfectly good implementations of DFS can have entirely different outputs if they simply choose to visit the nodes in a different order, such as starting from the left (A -> B) rather than the right (A -> D) side.