How to prepare depth-first algorithm & breadth-first algorithm in response to handwritten code for written test?

1. What is depth-first algorithm? What is the breadth-first algorithm?

Does such a high-ranking name sound like a befuddled face? Don’t worry, I will give you a popular example. I don’t know if you have read the story of "Little Tadpole Looking for Mom". Now I will use this example to give Everyone explain.

The picture I drew below is ugly, but it can be seen.
insert image description here
The little tadpole above is at position 0, and it may appear on the last floor if it wants to find its mother, so how can the little tadpole go?

If it is a breadth-first search, the tadpole can find a path according to each layer, and finally, the result of the search is #0#1#2#3#4#5...

If it is a depth-first search, the tadpole can follow a route to the end, return to the original fork point after walking, and choose another path to continue walking until the end. The search result is #0#2#6#14#13#5#12#11#1#4#10...

(ps: the depth-first algorithm is also called DFS, and the breadth-first algorithm is also called BFS)

2. Breadth-first algorithm usage scenarios

1. The problem of connected blocks
includes graphs, trees, two-dimensional arrays (matrixes), etc., that is, to find a whole connected block through a point diffusion.
2. Hierarchical traversal
Give you a tree, output according to each layer.
Given a simple graph (no direction, no weight), find the shortest path. (In fact, it is the same as tree traversal, except that the graph may traverse to duplicate nodes, we only need to remove the duplicates each time, and finally take the number of layers when the target node is first reached).
3. Topological sorting
Give you a graph in the current direction, find its topological sorting, or ask whether there is a topological sorting, or find the smallest topological sorting, or ask whether it is unique (the essence is the same). The classic question is that you need to take another class before taking a certain class. Now you are given a number of courses and some courses need to be online in other courses. How should you arrange the courses. At this time, if you draw the subject and add the direction, it is a topological problem.

3. Breadth-first algorithm template

class Solution {
    
    
    public List<List<Integer>> levelOrder(TreeNode root) {
    
    
        List<List<Integer>> res = new ArrayList<>();
        if(root == null){
    
    
            return res;
        }
        // 1. 定义队列
        Queue<TreeNode> queue = new LinkedList<>();
        // 2.加入初始条件
        queue.offer(root);
        // 3. 队列不为空的while循环
        while(!queue.isEmpty()){
    
    
            List<Integer> oneRes = new ArrayList<>();
            int n = queue.size();
            // 3.1 for循环将队列元素逐一取出进行处理
            for(int i = 0;i < n;++i){
    
    
                TreeNode temp = queue.poll();
                // 3.0 业务处理
                oneRes.add(temp.val);
                // 3.2 将下一条件放入队列中
                if(temp.left!=null){
    
    
                    queue.offer(temp.left);
                }
                if(temp.right!=null){
    
    
                    queue.offer(temp.right);
                }
            }
            // 3.3 将符合条件的一种结果放入结果集中
            res.add(oneRes);
        }
        // 4. 返回结果集
        return res;
    }
}

In addition, the serialization and deserialization of binary trees can also be implemented with the breadth-first algorithm. If the title specifies which method to use, the serialization of the breadth-first algorithm will be more intuitive than the depth-first algorithm.

4. Depth-first algorithm usage scenarios

1. Graph or tree traversal (including binary tree traversal, connected graph, etc.) (sometimes it is not an obvious graph or tree, but you need to manually simulate the tree or graph yourself).
2. Permutation (given some elements, return all possible permutations) (eg (1, 2, 3), the permutations are (123) (132) (213) (231) (312) (321)).
3. Combination (given some elements, return all possible combinations) (eg (1, 2, 3), the combination has (empty) (1) (2) (3) (12) (13) (23) (123 )).

When operating permutations and combinations, sometimes there will be repeated elements that lead to repeated results. In addition to using HashSet to remove duplicates, it is more appropriate to use the method of selecting representatives. Selecting representatives means selecting a suitable representative, and the rest of the repeated elements are directly ignored.

5. Depth-first algorithm template

//模板2
void dfs()//参数用来表示状态  
{
    
      
    if(到达终点状态){
    
      
        ...//根据题意添加  
        return;  
    }  
    if(越界或者是不合法状态)  
        return;  
    if(特殊状态)//剪枝
        return ;
    for(扩展方式){
    
      
        if(扩展方式所达到状态合法){
    
      
            修改操作;//根据题意来添加  
            标记;  
            dfs();  
            (还原标记)//是否还原标记根据题意  
            //如果加上(还原标记)就是 回溯法  
        }  
 
    }  
}  

6. Complexity of BFS and DFS

The time complexity is: O(V+E), V is the number of vertices, and E is the number of edges. The
space complexity of BFS is the queue size, which is related to the width.
The space complexity of DFS is the space occupied when calling recursion, which is related to the depth.

7. Implementation of BFS and DFS

BFS is generally implemented through queues.
DFS is generally implemented through recursion.

Guess you like

Origin blog.csdn.net/PaperJack/article/details/125134859