How to implement depth first search for graph with a non-recursive approach

前端 未结 13 1798
情话喂你
情话喂你 2020-11-28 22:00

I have spent lots of time on this issue. However, I can only find solutions with non-recursive methods for a tree: Non recursive for tree, or a recursive method for the grap

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 22:14

    The DFS logic should be:

    1) if the current node is not visited, visit the node and mark it as visited
    2) for all its neighbors that haven't been visited, push them to the stack

    For example, let's define a GraphNode class in Java:

    class GraphNode {
        int index;
        ArrayList neighbors;
    }
    

    and here is the DFS without recursion:

    void dfs(GraphNode node) {
        // sanity check
        if (node == null) {
            return;
        }
    
        // use a hash set to mark visited nodes
        Set set = new HashSet();
    
        // use a stack to help depth-first traversal
        Stack stack = new Stack();
        stack.push(node);
    
        while (!stack.isEmpty()) {
            GraphNode curr = stack.pop();
    
            // current node has not been visited yet
            if (!set.contains(curr)) {
                // visit the node
                // ...
    
                // mark it as visited
                set.add(curr);
            }
    
            for (int i = 0; i < curr.neighbors.size(); i++) {
                GraphNode neighbor = curr.neighbors.get(i);
    
                // this neighbor has not been visited yet
                if (!set.contains(neighbor)) {
                    stack.push(neighbor);
                }
            }
        }
    }
    

    We can use the same logic to do DFS recursively, clone graph etc.

提交回复
热议问题