深度优先搜索DFS

refer to : https://www.algoexpert.io/questions/Depth-first%20Search


深度优先搜索

  • 分析

深度遍历图结构,找到起始点(根结点),从起始点出发,深度搜索每一个分支,对于每一个分支,一直遍历到该分支的最底层,然后再遍历另外一个分支。

traverse a graph in a DFS way, from the root node, explore a specific branch, the first branch in our graph, all the way down as deep as we can before exploring the next branch。

从根结点出发,首先把根结点加入结果集,然后对根结点的每一个孩子结点调用dfs函数,每到达一个当前结点,把当前结点加入结果集,然后对于当前结点的每一个孩子结点,调用dfs函数。

call the depth-first-search function on each child node , one after the other , it is a sort of recursive way, but not really recursive, we just repeat recall 

when we are at a given node, we will add that node's name into the result array. then for every child in its children nodes, call the dfs function。

left most branch(A, B, E)---> inner left most branch(F, I)--->inner right most branch(J)--->C--->D, G, K--->H

  • 代码。  V顶点, E边
  • 时间复杂度:
    • O(V + E), 需要遍历每一个结点,V个结点,对于每一个结点,都要一个个遍历它们的孩子结点(for loop to call dfs function),多少条边就有多少个孩子结点。
  • 空间复杂度:
    • 结果集是一个v个结点的数组,adding a bunch of frames to call stack, as we go deeper and deeper in a branch, we keep adding frames to the call stack
    • we call dfs function on A, before we resolve this function, we call dfs on B, C, D; when we start with B, we need to call dfs on E and F, then before resolving F, we need to call bfs on I, J. 所以在算出A之前,我们先要算它的所有子结点,最坏的情况是,整个图只有一个大分支,从根部到叶子结点一条大分支,这个时候我们有V个frames on call stack.
  • class Node:
        def __init__(self, name):
            self.children = []
            self.name = name
    
        def addChild(self, name):
            self.children.append(Node(name))
            return self
    
        def depthFirstSearch(self, array):
            
            array.append(self.name) //O(V)
            for child in self.children:    //O(E)
                child.depthFirstSearch(array)
            return array
    class Program {
      static class Node {
        String name;
        List<Node> children = new ArrayList<Node>();
    
        public Node(String name) {
          this.name = name;
        }
    
        public List<String> depthFirstSearch(List<String> array) {
          // Write your code here.
                array.add(this.name);
                for(int i = 0; i < children.size();i++){
                    children.get(i).depthFirstSearch(array);
                }
          return array;
        }
    
        public Node addChild(String name) {
          Node child = new Node(name);
          children.add(child);
          return this;
        }
      }
    }
原文地址:https://www.cnblogs.com/LilyLiya/p/14251368.html